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:com.moz.fiji.commons.RefreshingReference.java

/**
 * Static factory constructor. Provides a default name for the thread the scheduler will
 * run on.// w ww. ja v  a 2  s . c om
 *
 * @param refreshPeriod Configures the refresh rate for the scheduler.
 * @param timeUnit Specifies the unit of time for the refreshPeriod.
 * @param refreshingLoader Used to initialize and refresh the cached value.
 * @param loopController Used to deterministically control refresh cycles during testing.
 * @param <U> The type that will be cached.
 * @return A new RefreshingReference.
 */
public static <U> RefreshingReference<U> create(final Long refreshPeriod, final TimeUnit timeUnit,
        final RefreshingLoader<U> refreshingLoader, final Optional<LoopController> loopController) {
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder().setNameFormat("refreshing-reference-%d");
    return new RefreshingReference<>(refreshPeriod, timeUnit, refreshingLoader, builder, loopController);
}

From source file:com.spotify.helios.testing.HeliosSoloLogService.java

@Override
protected ScheduledExecutorService executor() {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(serviceName()).setDaemon(true)
            .build();//from  w  w w.  j a v a 2s.c o m
    return Executors.newSingleThreadScheduledExecutor(threadFactory);
}

From source file:org.apache.distributedlog.feature.DynamicConfigurationFeatureProvider.java

public DynamicConfigurationFeatureProvider(String rootScope, DistributedLogConfiguration conf,
        StatsLogger statsLogger) {/* w  ww.j  av a  2  s. c  o m*/
    super(rootScope, conf, statsLogger);
    this.features = new ConcurrentHashMap<String, SettableFeature>();
    this.featuresConf = new ConcurrentBaseConfiguration();
    this.executorService = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat("DynamicConfigurationFeatureProvider-%d").build());
}

From source file:org.apache.bookkeeper.bookie.SyncThread.java

public SyncThread(ServerConfiguration conf, LedgerDirsListener dirsListener, LedgerStorage ledgerStorage,
        CheckpointSource checkpointSource) {
    this.dirsListener = dirsListener;
    this.ledgerStorage = ledgerStorage;
    this.checkpointSource = checkpointSource;
    ThreadFactoryBuilder tfb = new ThreadFactoryBuilder()
            .setNameFormat("SyncThread-" + conf.getBookiePort() + "-%d");
    this.executor = Executors.newSingleThreadScheduledExecutor(tfb.build());
    flushInterval = conf.getFlushInterval();
    LOG.debug("Flush Interval : {}", flushInterval);
}

From source file:qa.qcri.nadeef.core.pipeline.DirectIterator.java

@Override
protected java.util.Iterator<Violation> execute(Collection<Table> blocks) throws Exception {
    Tracer tracer = Tracer.getTracer(DirectIterator.class);
    ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("iterator-#" + MAX_THREAD_NUM + "-%d")
            .build();/*from w  w w. java 2 s  .c  om*/
    ExecutorService executor = Executors.newFixedThreadPool(MAX_THREAD_NUM, factory);
    Stopwatch stopwatch = Stopwatch.createStarted();

    ExecutionContext context = getCurrentContext();
    Rule rule = context.getRule();
    NonBlockingCollectionIterator<Violation> output = new NonBlockingCollectionIterator<>();
    try {
        if (rule.supportTwoTables()) {
            // Rule runs on two tables.
            executor.submit(new IteratorCallable(blocks, rule, context.getNewTuples(), output));
        } else {
            // Rule runs on each table.
            for (Table table : blocks)
                executor.submit(
                        new IteratorCallable(Arrays.asList(table), rule, context.getNewTuples(), output));
        }

        // wait until all the tasks are finished
        executor.shutdown();
        while (!executor.awaitTermination(10l, TimeUnit.MINUTES))
            ;
    } catch (InterruptedException ex) {
        tracer.err("Iterator is interrupted.", ex);
    } finally {
        executor.shutdown();
    }

    PerfReport.appendMetric(PerfReport.Metric.IteratorTime, stopwatch.elapsed(TimeUnit.MILLISECONDS));

    stopwatch.stop();
    return output;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.sharedcache.SharedCacheUploadService.java

@Override
protected void serviceInit(Configuration conf) throws Exception {
    enabled = conf.getBoolean(YarnConfiguration.SHARED_CACHE_ENABLED,
            YarnConfiguration.DEFAULT_SHARED_CACHE_ENABLED);
    if (enabled) {
        int threadCount = conf.getInt(YarnConfiguration.SHARED_CACHE_NM_UPLOADER_THREAD_COUNT,
                YarnConfiguration.DEFAULT_SHARED_CACHE_NM_UPLOADER_THREAD_COUNT);
        uploaderPool = Executors.newFixedThreadPool(threadCount,
                new ThreadFactoryBuilder().setNameFormat("Shared cache uploader #%d").build());
        scmClient = createSCMClient(conf);
        try {//w  ww.j  a  va  2s  .c  om
            fs = FileSystem.get(conf);
            localFs = FileSystem.getLocal(conf);
        } catch (IOException e) {
            LOG.error("Unexpected exception in getting the filesystem", e);
            throw new RuntimeException(e);
        }
    }
    super.serviceInit(conf);
}

From source file:org.metaservice.kryo.ClientHandler.java

@Override
public void received(final Connection connection, Object o) {
    if (o instanceof RegisterClientMessage) {
        RegisterClientMessage registerMessage = (RegisterClientMessage) o;
        LOGGER.info("registering... " + registerMessage);
        IndividualClientHandler individualClientHandler;
        switch (registerMessage.getType()) {
        case POSTPROCESS:
            individualClientHandler = new IndividualClientHandler<>(
                    queueContainer.addPostProcessorQueue(registerMessage.getName()),
                    registerMessage.getMessageCount());
            break;
        case PROVIDER_CREATE:
            individualClientHandler = new IndividualClientHandler<>(
                    queueContainer.addProviderCreateQueue(registerMessage.getName()),
                    registerMessage.getMessageCount());
            break;
        case PROVIDER_REFRESH:
            individualClientHandler = new IndividualClientHandler<>(
                    queueContainer.addProviderRefreshQueue(registerMessage.getName()),
                    registerMessage.getMessageCount());
            break;
        default:/*ww  w .j  a va2 s  .  c  om*/
            LOGGER.warn("UNKNOWN TYPE " + registerMessage.getType());
            return;
        }
        LOGGER.debug("on Connection {}", connection.getID());
        ThreadFactoryBuilder builder = new ThreadFactoryBuilder()
                .setNameFormat("indivClient-" + registerMessage.getName() + "-%d");
        listenerMap.put(connection.getID(), new Listener.ThreadedListener(individualClientHandler,
                Executors.newFixedThreadPool(1, builder.build())));
        individualClientHandler.init(connection);
    } else {
        if (listenerMap.containsKey(connection.getID())) {
            listenerMap.get(connection.getID()).received(connection, o);
        } /*else{
          //gets all write messages and keep alive messages
          LOGGER.warn("no listener to inform for message {}", o.getClass().getName());
          }*/
    }
}

From source file:org.wso2.carbon.event.processor.core.internal.storm.manager.StormManagerServer.java

public StormManagerServer(String hostName, int port) {

    try {/*from w  w w  . j a v a2  s.  c o m*/
        stormManagerService = new StormManagerServiceImpl(hostName + ":" + port);
        TServerSocket serverTransport = new TServerSocket(new InetSocketAddress(hostName, port));
        StormManagerService.Processor<StormManagerServiceImpl> processor = new StormManagerService.Processor<StormManagerServiceImpl>(
                stormManagerService);
        stormManagerServer = new TThreadPoolServer(
                new TThreadPoolServer.Args(serverTransport).processor(processor));
        Thread thread = new Thread(new ServerThread(stormManagerServer));
        thread.start();

        log.info("CEP Storm Management Thrift Server started on " + hostName + ":" + port);
        executorService = new ScheduledThreadPoolExecutor(3, new ThreadFactoryBuilder()
                .setNameFormat("Thread pool- component - StormManagerServer.executorService").build());
    } catch (TTransportException e) {
        log.error("Cannot start Storm Manager Server on " + hostName + ":" + port, e);
    }
}

From source file:com.codeabovelab.dm.cluman.ds.container.ContainerInfoUpdater.java

@Autowired
public ContainerInfoUpdater(DockerServices dockerServices, ContainerStorageImpl containerStorage,
        @Qualifier(NodeEvent.BUS) Subscriptions<NodeEvent> nodeSubs,
        @Qualifier(DockerServiceEvent.BUS) Subscriptions<DockerServiceEvent> dockerSubs,
        @Qualifier(DockerLogEvent.BUS) Subscriptions<DockerLogEvent> dockerLogSubs) {
    this.dockerServices = dockerServices;
    this.containerStorage = containerStorage;
    nodeSubs.subscribe(this::onNodeEvent);
    dockerSubs.subscribe(this::onDockerEvent);
    dockerLogSubs.subscribe(this::onDockerLogEvent);
    this.scheduledService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
            .setDaemon(true).setNameFormat(getClass().getSimpleName() + "-%d").build());
    this.scheduledNodes = new ConcurrentHashMap<>();
}

From source file:com.facebook.buck.cli.CommandThreadManager.java

public CommandThreadManager(String name, ConcurrencyLimit concurrencyLimit, long shutdownTimeout,
        TimeUnit shutdownTimeoutUnit) {
    this.threadGroup = new ThreadGroup(name);
    this.executor = new WeightedListeningExecutorService(
            new ListeningMultiSemaphore(concurrencyLimit.maximumAmounts,
                    concurrencyLimit.resourceAllocationFairness),
            /* defaultPermits */ concurrencyLimit.defaultAmounts,
            listeningDecorator(//  ww w  . ja  v  a2s . c  o m
                    new LimitedThreadPoolExecutor(new ThreadFactoryBuilder().setNameFormat(name + "-%d")
                            .setThreadFactory(new CommandThreadFactory(r -> new Thread(threadGroup, r)))
                            .build(), new LinkedBlockingStack<Runnable>(), concurrencyLimit)));
    this.shutdownTimeout = shutdownTimeout;
    this.shutdownTimeoutUnit = shutdownTimeoutUnit;
}