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

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

Introduction

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

Prototype

public ThreadFactory build() 

Source Link

Document

Returns a new thread factory using the options supplied during the building process.

Usage

From source file:org.apache.bookkeeper.client.UpdateLedgerOp.java

/**
 * Update the bookie id present in the ledger metadata.
 *
 * @param oldBookieId//from ww  w  .j  a v  a2  s.c om
 *            current bookie id
 * @param newBookieId
 *            new bookie id
 * @param rate
 *            number of ledgers updating per second (default 5 per sec)
 * @param limit
 *            maximum number of ledgers to update (default: no limit). Stop
 *            update if reaching limit
 * @param progressable
 *            report progress of the ledger updates
 * @throws IOException
 *             if there is an error when updating bookie id in ledger
 *             metadata
 * @throws InterruptedException
 *             interrupted exception when update ledger meta
 */
public void updateBookieIdInLedgers(final BookieSocketAddress oldBookieId,
        final BookieSocketAddress newBookieId, final int rate, final int limit,
        final UpdateLedgerNotifier progressable) throws BKException, IOException {

    final ThreadFactoryBuilder tfb = new ThreadFactoryBuilder().setNameFormat("UpdateLedgerThread")
            .setDaemon(true);
    final ExecutorService executor = Executors.newSingleThreadExecutor(tfb.build());
    final AtomicInteger issuedLedgerCnt = new AtomicInteger();
    final AtomicInteger updatedLedgerCnt = new AtomicInteger();
    final Future<?> updateBookieCb = executor.submit(new Runnable() {

        @Override
        public void run() {
            updateLedgers(oldBookieId, newBookieId, rate, limit, progressable);
        }

        private void updateLedgers(final BookieSocketAddress oldBookieId, final BookieSocketAddress newBookieId,
                final int rate, final int limit, final UpdateLedgerNotifier progressable) {
            try {
                final AtomicBoolean stop = new AtomicBoolean(false);
                final Set<Long> outstandings = Collections
                        .newSetFromMap(new ConcurrentHashMap<Long, Boolean>());
                final RateLimiter throttler = RateLimiter.create(rate);
                final Iterator<Long> ledgerItr = admin.listLedgers().iterator();
                final CountDownLatch syncObj = new CountDownLatch(1);

                // iterate through all the ledgers
                while (ledgerItr.hasNext() && !stop.get()) {
                    // throttler to control updates per second
                    throttler.acquire();

                    final Long lId = ledgerItr.next();
                    final ReadLedgerMetadataCb readCb = new ReadLedgerMetadataCb(bkc, lId, oldBookieId,
                            newBookieId);
                    outstandings.add(lId);

                    FutureCallback<Void> updateLedgerCb = new UpdateLedgerCb(lId, stop, issuedLedgerCnt,
                            updatedLedgerCnt, outstandings, syncObj, progressable);
                    Futures.addCallback(readCb.getFutureListener(), updateLedgerCb);

                    issuedLedgerCnt.incrementAndGet();
                    if (limit != Integer.MIN_VALUE && issuedLedgerCnt.get() >= limit || !ledgerItr.hasNext()) {
                        stop.set(true);
                    }
                    bkc.getLedgerManager().readLedgerMetadata(lId, readCb);
                }
                // waiting till all the issued ledgers are finished
                syncObj.await();
            } catch (IOException ioe) {
                LOG.error("Exception while updating ledger", ioe);
                throw new RuntimeException("Exception while updating ledger", ioe.getCause());
            } catch (InterruptedException ie) {
                LOG.error("Exception while updating ledger metadata", ie);
                Thread.currentThread().interrupt();
                throw new RuntimeException("Exception while updating ledger", ie.getCause());
            }
        }
    });
    try {
        // Wait to finish the issued ledgers.
        updateBookieCb.get();
    } catch (ExecutionException ee) {
        throw new IOException("Exception while updating ledger", ee);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new IOException("Exception while updating ledger", ie);
    } finally {
        executor.shutdown();
    }
}

From source file:org.apache.phoenix.trace.TraceWriter.java

public void start() {

    traceSpanReceiver = getTraceSpanReceiver();
    if (traceSpanReceiver == null) {
        LOG.warn("No receiver has been initialized for TraceWriter. Traces will not be written.");
        LOG.warn("Restart Phoenix to try again.");
        return;/*from   w w  w. j  a va  2 s.c  om*/
    }

    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    builder.setDaemon(true).setNameFormat("PHOENIX-METRICS-WRITER");
    executor = Executors.newScheduledThreadPool(this.numThreads, builder.build());

    for (int i = 0; i < this.numThreads; i++) {
        executor.scheduleAtFixedRate(new FlushMetrics(), 0, 10, TimeUnit.SECONDS);
    }

    LOG.info("Writing tracing metrics to phoenix table");
}

From source file:org.apache.bookkeeper.stream.common.Scheduler.java

private Scheduler(String name, int numExecutors) {
    Preconditions.checkArgument(StringUtils.isNotBlank(name), "Require a not-blank scheduler name");
    Preconditions.checkArgument(numExecutors > 0, "Require positive value for num executors");

    this.name = name;
    this.executors = new ListeningScheduledExecutorService[numExecutors];
    for (int i = 0; i < numExecutors; i++) {
        StringBuilder sb = new StringBuilder(name);
        sb.append("-executor-").append(i).append("-%d");
        ThreadFactoryBuilder tfb = new ThreadFactoryBuilder().setNameFormat(sb.toString());
        executors[i] = MoreExecutors//from w  w  w  .  j a  v a  2  s .com
                .listeningDecorator(Executors.newSingleThreadScheduledExecutor(tfb.build()));
    }
    this.random = new Random(System.currentTimeMillis());
}

From source file:com.kolich.curacao.util.AsyncServletExecutorServiceFactory.java

public final ExecutorService build() {
    final ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    if (threadNameFormat_ != null) {
        builder.setNameFormat(threadNameFormat_);
    }//from w ww .ja  v  a  2  s .  com
    if (priority_ != null) {
        builder.setPriority(priority_);
    }
    if (useDaemon_ != null) {
        builder.setDaemon(useDaemon_);
    }
    return (size_ > 0) ?
    // Fixed sized thread pool (no more than N-threads).
            newFixedThreadPool(size_, builder.build()) :
            // Unbounded thread pool, will grow as needed.
            newCachedThreadPool(builder.build());
}

From source file:com.proofpoint.event.collector.MainModule.java

@Provides
@Singleton// w w w. j  a  va 2 s  .co  m
@Named("ScheduledCombinerLowPriorityExecutor")
private ScheduledExecutorService createScheduledCombinerLowPriorityExecutor(ServerConfig config) {
    ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder().setDaemon(true);
    if (config.getCombinerLowPriorityEventTypes().size() <= 0) {
        threadFactoryBuilder.setNameFormat("StoredObjectCombiner-Low-Disabled-Should-Not-Be-Used");
    } else {
        threadFactoryBuilder.setNameFormat("StoredObjectCombiner-Low-%s");
    }

    return newSingleThreadScheduledExecutor(threadFactoryBuilder.build());
}

From source file:org.opendaylight.genius.interfacemanager.pmcounters.NodeConnectorStatsImpl.java

private ThreadFactory getThreadFactory(String threadNameFormat) {
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    builder.setNameFormat(threadNameFormat);
    builder.setUncaughtExceptionHandler((thread, exception) -> LOG
            .error("Received Uncaught Exception event in Thread: {}", thread.getName(), exception));
    return builder.build();
}

From source file:org.apache.hadoop.hbase.thrift.TBoundedThreadPoolServer.java

public TBoundedThreadPoolServer(Args options, ThriftMetrics metrics) {
    super(options);

    if (options.maxQueuedRequests > 0) {
        this.callQueue = new CallQueue(new LinkedBlockingQueue<Call>(options.maxQueuedRequests), metrics);
    } else {/*from w  w  w  . j  a  v  a2s .c  o m*/
        this.callQueue = new CallQueue(new SynchronousQueue<Call>(), metrics);
    }

    ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
    tfb.setDaemon(true);
    tfb.setNameFormat("thrift-worker-%d");
    executorService = new ThreadPoolExecutor(options.minWorkerThreads, options.maxWorkerThreads,
            options.threadKeepAliveTimeSec, TimeUnit.SECONDS, this.callQueue, tfb.build());
    serverOptions = options;
}

From source file:org.apache.hadoop.hbase.replication.ReplicationTableBase.java

/**
 * Sets up the thread pool executor used to build the Replication Table in the background
 * @return the configured executor/*from  ww  w .  j a  v  a 2s . c om*/
 */
private Executor setUpExecutor() {
    ThreadPoolExecutor tempExecutor = new ThreadPoolExecutor(NUM_INITIALIZE_WORKERS, NUM_INITIALIZE_WORKERS,
            100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
    tfb.setNameFormat("ReplicationTableExecutor-%d");
    tfb.setDaemon(true);
    tempExecutor.setThreadFactory(tfb.build());
    return tempExecutor;
}

From source file:com.notifier.desktop.ApplicationModule.java

@Override
protected void configure() {
    bind(Application.class);

    bind(SwtManager.class).to(SwtManagerImpl.class);
    bind(TrayManager.class).to(SwtTrayManager.class);
    bind(PreferencesDialog.class);

    bind(NotificationManager.class).to(NotificationManagerImpl.class);
    bind(new TypeLiteral<NotificationParser<byte[]>>() {
    }).to(MultiNotificationParser.class);
    bind(DeviceManager.class).to(DeviceManagerImpl.class);

    bind(NotificationBroadcaster.class).annotatedWith(Tray.class).to(TrayNotificationBroadcaster.class);
    bind(NotificationBroadcaster.class).annotatedWith(Growl.class).to(GrowlNotificationBroadcaster.class);
    bind(NotificationBroadcaster.class).annotatedWith(Libnotify.class)
            .to(LibnotifyNotificationBroadcaster.class);
    bind(InstantMessagingNotificationBroadcaster.class).annotatedWith(Msn.class)
            .to(MsnNotificationBroadcaster.class);

    bind(WifiTransport.class).to(NioWifiTransport.class);
    bind(BluetoothTransport.class).to(BluetoothTransportImpl.class);
    bind(UsbTransport.class).to(UsbTransportImpl.class);
    bind(UsbPortClient.class);

    bind(NetworkManager.class).to(NetworkManagerImpl.class);
    bind(UpnpManager.class).to(UpnpManagerImpl.class);
    bind(UpdateManager.class).to(UpdateManagerImpl.class);
    bind(ServiceServer.class).to(ServiceServerImpl.class);
    bind(OperatingSystemProcessManager.class).to(OperatingSystemProcessManagerImpl.class);

    ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
    threadFactoryBuilder.setNameFormat("task-%s");
    threadFactoryBuilder.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from  w  ww . ja  v  a2 s  . c o m*/
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Uncaught exception", e);
        }
    });
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4,
            threadFactoryBuilder.build());
    bind(ExecutorService.class).toInstance(executorService);
    bind(ScheduledExecutorService.class).toInstance(executorService);
}

From source file:org.opendaylight.netvirt.vpnmanager.ArpScheduler.java

private ThreadFactory getThreadFactory(String threadNameFormat) {
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    builder.setNameFormat(threadNameFormat);
    builder.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override//from  ww w. jav a  2 s .  c  o  m
        public void uncaughtException(Thread t, Throwable e) {
            LOG.error("Received Uncaught Exception event in Thread: {}", t.getName(), e);
        }
    });
    return builder.build();
}