Example usage for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder

List of usage examples for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder.

Prototype

public ThreadFactoryBuilder() 

Source Link

Document

Creates a new ThreadFactory builder.

Usage

From source file:org.graylog2.inputs.transports.TcpTransport.java

private static Executor executorService(final String executorName, final String threadNameFormat,
        final MetricRegistry metricRegistry) {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(threadNameFormat).build();
    return new InstrumentedExecutorService(Executors.newCachedThreadPool(threadFactory), metricRegistry,
            name(TcpTransport.class, executorName, "executor-service"));
}

From source file:com.datastax.driver.core.ThreadingOptions.java

/**
 * Builds a thread factory for the threads created by a given executor.
 * <p/>//from ww  w . ja v a  2 s  .  c om
 * This is used by the default implementations in this class, and also internally to create the Netty I/O pool.
 *
 * @param clusterName  the name of the cluster, as specified by
 *                     {@link com.datastax.driver.core.Cluster.Builder#withClusterName(String)}.
 * @param executorName a name that identifies the executor.
 * @return the thread factory.
 */
public ThreadFactory createThreadFactory(String clusterName, String executorName) {
    return new ThreadFactoryBuilder().setNameFormat(clusterName + "-" + executorName + "-%d")
            // Back with Netty's thread factory in order to create FastThreadLocalThread instances. This allows
            // an optimization around ThreadLocals (we could use DefaultThreadFactory directly but it creates
            // slightly different thread names, so keep we keep a ThreadFactoryBuilder wrapper for backward
            // compatibility).
            .setThreadFactory(new DefaultThreadFactory("ignored name")).build();
}

From source file:org.apache.beam.runners.core.metrics.MetricsPusher.java

public void start() {
    if (!(metricsSink instanceof NoOpMetricsSink)) {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setDaemon(true).setNameFormat("MetricsPusher-thread").build());
        scheduledFuture = scheduler.scheduleAtFixedRate(() -> run(), 0, period, TimeUnit.SECONDS);
    }//from   w  w  w  .j av a  2s  .  co  m
}

From source file:org.apache.pulsar.functions.windowing.WaterMarkEventGenerator.java

/**
 * Creates a new WatermarkEventGenerator.
 * @param windowManager The window manager this generator will submit watermark events to
 * @param intervalMs The generator will check if it should generate a watermark event with this intervalMs
 * @param eventTsLagMs The max allowed lag behind the last watermark event before an event is considered late
 * @param inputTopics The input topics this generator is expected to handle
 *//*from w ww .j ava  2s . c o  m*/
public WaterMarkEventGenerator(WindowManager<T> windowManager, long intervalMs, long eventTsLagMs,
        Set<String> inputTopics, Context context) {
    this.windowManager = windowManager;
    topicToTs = new ConcurrentHashMap<>();

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("watermark-event-generator-%d")
            .setDaemon(true).build();
    executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);

    this.intervalMs = intervalMs;
    this.eventTsLagMs = eventTsLagMs;
    this.inputTopics = inputTopics;
    this.context = context;
}

From source file:io.joynr.dispatching.DispatcherTestModule.java

@Override
protected void configure() {

    bind(MessageSender.class).to(MessageSenderReceiverMock.class);
    bind(MessageReceiver.class).to(MessageSenderReceiverMock.class);
    bind(RequestReplyManager.class).to(RequestReplyManagerImpl.class);
    bind(MessageRouter.class).to(MessageRouterImpl.class);
    bind(RoutingTable.class).to(RoutingTableImpl.class).asEagerSingleton();
    bind(Dispatcher.class).to(DispatcherImpl.class);
    bind(SubscriptionManager.class).to(SubscriptionManagerImpl.class);
    bind(PublicationManager.class).to(PublicationManagerImpl.class);

    requestStaticInjection(RpcUtils.class, Request.class, JoynrMessagingConnectorFactory.class);

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("joynr.Cleanup-%d").build();
    ScheduledExecutorService cleanupExecutor = Executors.newSingleThreadScheduledExecutor(namedThreadFactory);
    bind(ScheduledExecutorService.class).annotatedWith(Names.named(JOYNR_SCHEDULER_CLEANUP))
            .toInstance(cleanupExecutor);
}

From source file:org.eclipse.che.workspace.infrastructure.docker.monit.DockerMachineStopDetector.java

@Inject
public DockerMachineStopDetector(DockerConnector dockerConnector) {
    this.dockerConnector = dockerConnector;
    this.handlers = new ConcurrentHashMap<>();
    this.containersOomTimestamps = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build();
    this.executorService = Executors
            .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("DockerMachineStopDetector-%d")
                    .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()).setDaemon(true)
                    .build());/*from www.j  av a 2s  .  co  m*/
}

From source file:org.apache.tephra.txprune.TransactionPruningService.java

@Override
protected void startUp() throws Exception {
    if (!pruneEnabled) {
        LOG.info("Transaction pruning is not enabled");
        return;//from  w w  w.  ja  v a  2  s . c o  m
    }

    LOG.info("Starting {}...", this.getClass().getSimpleName());
    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat("tephra-pruning-thread").setDaemon(true).build());

    Map<String, TransactionPruningPlugin> plugins = initializePlugins();
    long txMaxLifetimeMillis = TimeUnit.SECONDS.toMillis(
            conf.getInt(TxConstants.Manager.CFG_TX_MAX_LIFETIME, TxConstants.Manager.DEFAULT_TX_MAX_LIFETIME));
    long txPruneBufferMillis = TimeUnit.SECONDS
            .toMillis(conf.getLong(TxConstants.TransactionPruning.PRUNE_GRACE_PERIOD,
                    TxConstants.TransactionPruning.DEFAULT_PRUNE_GRACE_PERIOD));
    pruneRunnable = getTxPruneRunnable(txManager, plugins, txMaxLifetimeMillis, txPruneBufferMillis);
    scheduledExecutorService.scheduleAtFixedRate(pruneRunnable, scheduleInterval, scheduleInterval,
            TimeUnit.SECONDS);
    LOG.info("Scheduled {} plugins with interval {} seconds", plugins.size(), scheduleInterval);
}

From source file:org.sonar.server.notification.NotificationDaemon.java

@Override
public void start() {
    executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
            .setNameFormat(THREAD_NAME_PREFIX + "%d").setPriority(Thread.MIN_PRIORITY).build());
    executorService.scheduleWithFixedDelay(() -> {
        try {/*w w w.  j av a  2  s .c o  m*/
            processQueue();
        } catch (Exception e) {
            LOG.error("Error in NotificationService", e);
        }
    }, 0, delayInSeconds, TimeUnit.SECONDS);
    LOG.info("Notification service started (delay {} sec.)", delayInSeconds);
}

From source file:org.eclipse.che.api.system.server.SystemManager.java

/**
 * Stops some of the system services preparing system to lighter shutdown.
 * System status is changed from {@link SystemStatus#RUNNING} to
 * {@link SystemStatus#PREPARING_TO_SHUTDOWN}.
 *
 * @throws ConflictException// ww w . j a  v  a 2 s .  c o m
 *         when system status is different from running
 */
public void stopServices() throws ConflictException {
    if (!statusRef.compareAndSet(RUNNING, PREPARING_TO_SHUTDOWN)) {
        throw new ConflictException(
                "System shutdown has been already called, system status: " + statusRef.get());
    }
    ExecutorService exec = Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder().setDaemon(false).setNameFormat("ShutdownSystemServicesPool")
                    .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()).build());
    exec.execute(ThreadLocalPropagateContext.wrap(this::doStopServices));
    exec.shutdown();
}

From source file:com.tascape.qa.th.SuiteRunner.java

public int startExecution() throws IOException, InterruptedException, SQLException, XMLStreamException {
    File dir = SYS_CONFIG.getLogPath().resolve(execId).toFile();
    LOG.info("Create suite execution log directory {}", dir);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Cannot create directory " + dir);
    }// ww w  .ja  v  a2  s.  co  m
    this.logAppProperties(dir);

    int threadCount = SYS_CONFIG.getExecutionThreadCount();
    LOG.info("Start execution engine with {} thread(s)", threadCount);
    int len = (threadCount + "").length();
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("t%0" + len + "d").build();
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount, namedThreadFactory);
    CompletionService<TestResult> completionService = new ExecutorCompletionService<>(executorService);

    LOG.info("Start to acquire test cases to execute");
    int numberOfFailures = 0;
    try {
        List<TestResult> tcrs = this.filter(this.db.getQueuedTestCaseResults(this.execId, 100));
        while (!tcrs.isEmpty()) {
            List<Future<TestResult>> futures = new ArrayList<>();

            for (TestResult tcr : tcrs) {
                LOG.info("Submit test case {}", tcr.getTestCase().format());
                futures.add(completionService.submit(new TestRunnerJUnit4(db, tcr)));
            }
            LOG.debug("Total {} test cases submitted", futures.size());

            for (Future<TestResult> f : futures) {
                try {
                    Future<TestResult> future = completionService.take();
                    TestResult tcr = future.get();
                    if (tcr == null) {
                        continue;
                    }
                    String result = tcr.getResult().result();
                    LOG.info("Get result of test case {} - {}", tcr.getTestCase().format(), result);
                    if (!ExecutionResult.PASS.name().equals(result) && !result.endsWith("/0")) {
                        numberOfFailures++;
                    }
                } catch (Throwable ex) {
                    LOG.error("Error executing test thread", ex);
                    numberOfFailures++;
                }
            }

            tcrs = this.filter(this.db.getQueuedTestCaseResults(this.execId, 100));
        }
    } finally {
        AbstractSuite.getSuites().stream().forEach((suite) -> {
            try {
                suite.tearDown();
            } catch (Exception ex) {
                LOG.warn("Error tearing down suite {} -  {}", suite.getClass(), ex.getMessage());
            }
        });
    }
    executorService.shutdown();

    LOG.info("No more test case to run on this host, updating suite execution result");
    this.db.updateSuiteExecutionResult(this.execId);
    this.db.saveJunitXml(this.execId);
    return numberOfFailures;
}