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.opendaylight.atrium.util.AtriumTools.java

/**
 * Returns a thread factory that produces threads named according to the
 * supplied name pattern and from the specified thread-group. The thread
 * group name is expected to be specified in slash-delimited format, The
 * thread names will be produced by converting the thread group name into
 * dash-delimited format and pre-pended to the specified pattern.
 *
 * @param groupName/*from   w  w w .j  a v a 2  s .  c o m*/
 *            group name in slash-delimited format to indicate hierarchy
 * @param pattern
 *            name pattern
 * @return thread factory
 */
public static ThreadFactory groupedThreads(String groupName, String pattern) {
    return new ThreadFactoryBuilder().setThreadFactory(groupedThreadFactory(groupName))
            .setNameFormat(groupName.replace(AtriumGroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
            .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
            .build();
}

From source file:co.cask.hydrator.plugin.RunExternalProgramExecutor.java

@Override
protected void startUp() throws Exception {
    // We need two threads.
    // One thread for keep reading from input, write to process stdout and read from stdin.
    // The other for keep reading stderr and log.
    executor = Executors.newFixedThreadPool(2, new ThreadFactoryBuilder().setDaemon(true).build());

    // The Shutdown thread is to time the shutdown and kill the process if it timeout.
    shutdownThread = createShutdownThread();

    process = Runtime.getRuntime().exec(executable);
    executor.execute(createProcessRunnable(process));
    executor.execute(createLogRunnable(process));
}

From source file:org.opendaylight.faas.fabric.general.FabricFactory.java

public FabricFactory(final DataBroker dataProvider, final RpcProviderRegistry rpcRegistry,
        final NotificationProviderService notificationService) {

    ThreadFactory threadFact = new ThreadFactoryBuilder().setNameFormat("fabric-factory-%d").build();
    executor = Executors.newSingleThreadExecutor(threadFact);

    manageApi = new FabricManagementAPIProvider(dataProvider, rpcRegistry, executor, this);
    manageApi.start();/*from   w w  w . j  av  a 2  s .c  o  m*/

    resourceApi = new FabricResourceAPIProvider(dataProvider, rpcRegistry);
    resourceApi.start();

    serviceApi = new FabricServiceAPIProvider(dataProvider, rpcRegistry, executor);
    serviceApi.start();

    epRegister = new EndPointRegister(dataProvider, rpcRegistry, executor);
    epRegister.start();
}

From source file:org.apache.flume.conf.file.AbstractFileConfigurationProvider.java

@Override
public void start() {
    logger.info("Configuration provider starting");

    Preconditions.checkState(file != null, "The parameter file must not be null");

    executorService = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat("conf-file-poller-%d").build());

    FileWatcherRunnable fileWatcherRunnable = new FileWatcherRunnable();

    fileWatcherRunnable.file = file;/*from  w ww.  j ava 2  s  . c om*/
    fileWatcherRunnable.counterGroup = counterGroup;

    executorService.scheduleWithFixedDelay(fileWatcherRunnable, 0, 30, TimeUnit.SECONDS);

    lifecycleState = LifecycleState.START;

    logger.debug("Configuration provider started");
}

From source file:org.wso2.andes.kernel.distruptor.inbound.DisruptorBasedInboundEventManager.java

public DisruptorBasedInboundEventManager(SubscriptionStore subscriptionStore, MessagingEngine messagingEngine) {

    Integer bufferSize = AndesConfigurationManager.readValue(PERFORMANCE_TUNING_PUBLISHING_BUFFER_SIZE);
    Integer writeHandlerCount = AndesConfigurationManager
            .readValue(PERFORMANCE_TUNING_PARALLEL_MESSAGE_WRITERS);
    Integer ackHandlerCount = AndesConfigurationManager.readValue(PERFORMANCE_TUNING_ACK_HANDLER_COUNT);
    Integer writerBatchSize = AndesConfigurationManager.readValue(PERFORMANCE_TUNING_MESSAGE_WRITER_BATCH_SIZE);
    Integer ackHandlerBatchSize = AndesConfigurationManager
            .readValue(PERFORMANCE_TUNING_ACKNOWLEDGEMENT_HANDLER_BATCH_SIZE);

    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("Disruptor Inbound Event Thread %d").build();
    ExecutorService executorPool = Executors.newCachedThreadPool(namedThreadFactory);

    Disruptor<InboundEvent> disruptor;
    disruptor = new Disruptor<InboundEvent>(InboundEvent.getFactory(), bufferSize, executorPool,
            ProducerType.MULTI, new BlockingWaitStrategy());

    disruptor.handleExceptionsWith(new InboundLogExceptionHandler());

    ConcurrentBatchEventHandler[] concurrentBatchEventHandlers = new ConcurrentBatchEventHandler[writeHandlerCount
            + ackHandlerCount];/*w w  w  .j  a  v a 2 s.  c  o m*/

    for (int turn = 0; turn < writeHandlerCount; turn++) {
        concurrentBatchEventHandlers[turn] = new ConcurrentBatchEventHandler(turn, writeHandlerCount,
                writerBatchSize, MESSAGE_EVENT, new MessageWriter(messagingEngine, writerBatchSize));
    }

    for (int turn = 0; turn < ackHandlerCount; turn++) {
        concurrentBatchEventHandlers[writeHandlerCount + turn] = new ConcurrentBatchEventHandler(turn,
                ackHandlerCount, ackHandlerBatchSize, ACKNOWLEDGEMENT_EVENT, new AckHandler(messagingEngine));
    }

    // Pre processor runs first then Write handlers and ack handlers run in parallel. State event handler comes
    // after them
    disruptor.handleEventsWith(new MessagePreProcessor(subscriptionStore)).then(concurrentBatchEventHandlers);

    // State event handler should run at last.
    // State event handler update the state of Andes after other handlers work is done.
    disruptor.after(concurrentBatchEventHandlers).handleEventsWith(new StateEventHandler(messagingEngine));

    ringBuffer = disruptor.start();
}

From source file:com.coinomi.core.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    this.wallet = checkNotNull(wallet, "Cannot save a null wallet");
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file, "Cannot save to a null file");
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit, "Cannot use a null delay time unit");

    this.saver = new Callable<Void>() {
        @Override//from   ww w. j  a  v  a2  s .  c o m
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet");
            saveNowInternal();
            return null;
        }
    };
}

From source file:com.reddcoin.core.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    this.wallet = checkNotNull(wallet);
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file);
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit);

    this.saver = new Callable<Void>() {
        @Override//w w  w. j av  a2 s .c o m
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet");
            saveNowInternal();
            return null;
        }
    };
}

From source file:com.google.worldcoin.wallet.WalletFiles.java

public WalletFiles(final Wallet wallet, File file, long delay, TimeUnit delayTimeUnit) {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Wallet autosave thread").setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
    Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
    if (handler != null)
        builder.setUncaughtExceptionHandler(handler);
    // An executor that starts up threads when needed and shuts them down later.
    this.executor = new ScheduledThreadPoolExecutor(1, builder.build());
    this.executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    this.executor.allowCoreThreadTimeOut(true);
    this.wallet = checkNotNull(wallet);
    // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access.
    this.file = checkNotNull(file);
    this.savePending = new AtomicBoolean();
    this.delay = delay;
    this.delayTimeUnit = checkNotNull(delayTimeUnit);

    this.saver = new Callable<Void>() {
        @Override/*from   ww w .  ja v  a  2s .c  o  m*/
        public Void call() throws Exception {
            // Runs in an auto save thread.
            if (!savePending.getAndSet(false)) {
                // Some other scheduled request already beat us to it.
                return null;
            }
            log.info("Background saving wallet, last seen block is {}/{}", wallet.getLastBlockSeenHeight(),
                    wallet.getLastBlockSeenHash());
            saveNowInternal();
            return null;
        }
    };
}

From source file:com.twitter.aurora.scheduler.periodic.PeriodicTaskLauncher.java

@Inject
PeriodicTaskLauncher(ShutdownRegistry shutdownRegistry, Preempter preeempter,
        @PeriodicTaskInterval Amount<Long, Time> taskInterval) {

    this.shutdownRegistry = checkNotNull(shutdownRegistry);
    this.preeempter = checkNotNull(preeempter);
    this.taskInterval = checkNotNull(taskInterval);

    executor = Executors.newScheduledThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat("Scheduler-Periodic-Task-%d").setDaemon(true).build());
}

From source file:org.apache.kylin.cube.cuboid.algorithm.greedy.GreedyAlgorithm.java

@Override
public List<Long> start(double spaceLimit) {
    logger.info("Greedy Algorithm started.");
    executor = Executors.newFixedThreadPool(THREAD_NUM,
            new ThreadFactoryBuilder().setNameFormat("greedy-algorithm-benefit-calculator-pool-%d").build());

    getBenefitPolicy().initBeforeStart();

    //Initial mandatory cuboids
    selected.clear();/*from   w ww  .  j  a va2 s  .  c  o  m*/
    double remainingSpace = spaceLimit;
    for (Long mandatoryOne : getCuboidStats().getAllCuboidsForMandatory()) {
        selected.add(mandatoryOne);
        if (getCuboidStats().getCuboidSize(mandatoryOne) != null) {
            remainingSpace -= getCuboidStats().getCuboidSize(mandatoryOne);
        }
    }
    //Initial remaining cuboid set
    remaining.clear();
    remaining.addAll(getCuboidStats().getAllCuboidsForSelection());

    long round = 0;
    while (true) {
        if (shouldCancel()) {
            break;
        }
        // Choose one cuboId having the maximum benefit per unit space in all available list
        CuboidBenefitModel best = recommendBestOne();
        // If return null, then we should finish the process and return
        if (best == null) {
            break;
        }
        // If we finally find the cuboid selected does not meet a minimum threshold of benefit (for
        // example, a cuboid with 0.99M roll up from a parent cuboid with 1M
        // rows), then we should finish the process and return
        if (!getBenefitPolicy().ifEfficient(best)) {
            break;
        }

        remainingSpace -= getCuboidStats().getCuboidSize(best.getCuboidId());
        // If we finally find there is no remaining space,  then we should finish the process and return
        if (remainingSpace <= 0) {
            break;
        }
        selected.add(best.getCuboidId());
        remaining.remove(best.getCuboidId());
        getBenefitPolicy().propagateAggregationCost(best.getCuboidId(), selected);
        round++;
        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Recommend in round %d : %s", round, best.toString()));
        }
    }

    executor.shutdown();

    List<Long> excluded = Lists.newArrayList(remaining);
    remaining.retainAll(selected);
    Preconditions.checkArgument(remaining.size() == 0,
            "There should be no intersection between excluded list and selected list.");
    logger.info("Greedy Algorithm finished.");

    if (logger.isTraceEnabled()) {
        logger.trace("Excluded cuboidId size:" + excluded.size());
        logger.trace("Excluded cuboidId detail:");
        for (Long cuboid : excluded) {
            logger.trace(String.format("cuboidId %d and Cost: %d and Space: %f", cuboid,
                    getCuboidStats().getCuboidQueryCost(cuboid), getCuboidStats().getCuboidSize(cuboid)));
        }
        logger.trace("Total Space:" + (spaceLimit - remainingSpace));
        logger.trace(
                "Space Expansion Rate:" + (spaceLimit - remainingSpace) / getCuboidStats().getBaseCuboidSize());
    }
    return Lists.newArrayList(selected);
}