java.util.concurrent.ThreadFactory

Here are the examples of the java api class java.util.concurrent.ThreadFactory taken from open source projects.

1. NettyContext#prepare()

Project: jstorm
File: NettyContext.java
/**
     * initialization per Storm configuration
     */
@SuppressWarnings("rawtypes")
public void prepare(Map storm_conf) {
    this.storm_conf = storm_conf;
    int maxWorkers = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
    ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
    ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");
    if (maxWorkers > 0) {
        clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), maxWorkers);
    } else {
        clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory));
    }
    int otherWorkers = Utils.getInt(storm_conf.get(Config.TOPOLOGY_WORKERS), 1) - 1;
    int poolSize = Math.min(Math.max(1, otherWorkers), MAX_CLIENT_SCHEDULER_THREAD_POOL_SIZE);
    clientScheduleService = Executors.newScheduledThreadPool(poolSize, new NettyRenameThreadFactory("client-schedule-service"));
    reconnector = new ReconnectRunnable();
    new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
    isSyncMode = ConfigExtension.isNettySyncMode(storm_conf);
}

2. RpcChannelFactory#createServerChannelFactory()

Project: incubator-tajo
File: RpcChannelFactory.java
// Client must release the external resources
public static synchronized ServerSocketChannelFactory createServerChannelFactory(String name, int workerNum) {
    name = name + "-" + serverCount.incrementAndGet();
    if (LOG.isInfoEnabled()) {
        LOG.info("Create " + name + " ServerSocketChannelFactory. Worker:" + workerNum);
    }
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    ThreadFactory bossFactory = builder.setNameFormat(name + " Server Boss #%d").build();
    ThreadFactory workerFactory = builder.setNameFormat(name + " Server Worker #%d").build();
    NioServerBossPool bossPool = new NioServerBossPool(Executors.newCachedThreadPool(bossFactory), 1, ThreadNameDeterminer.CURRENT);
    NioWorkerPool workerPool = new NioWorkerPool(Executors.newCachedThreadPool(workerFactory), workerNum, ThreadNameDeterminer.CURRENT);
    return new NioServerSocketChannelFactory(bossPool, workerPool);
}

3. RpcChannelFactory#createClientChannelFactory()

Project: incubator-tajo
File: RpcChannelFactory.java
// Client must release the external resources
public static synchronized ClientSocketChannelFactory createClientChannelFactory(String name, int workerNum) {
    name = name + "-" + clientCount.incrementAndGet();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Create " + name + " ClientSocketChannelFactory. Worker:" + workerNum);
    }
    ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
    ThreadFactory bossFactory = builder.setNameFormat(name + " Boss #%d").build();
    ThreadFactory workerFactory = builder.setNameFormat(name + " Worker #%d").build();
    NioClientBossPool bossPool = new NioClientBossPool(Executors.newCachedThreadPool(bossFactory), 1, new HashedWheelTimer(), ThreadNameDeterminer.CURRENT);
    NioWorkerPool workerPool = new NioWorkerPool(Executors.newCachedThreadPool(workerFactory), workerNum, ThreadNameDeterminer.CURRENT);
    return new NioClientSocketChannelFactory(bossPool, workerPool);
}

4. NettyMapOutputHttpServer#init()

Project: hadoop-20
File: NettyMapOutputHttpServer.java
public synchronized void init(Configuration conf) {
    ThreadFactory bossFactory = new ThreadFactoryBuilder().setNameFormat("ShuffleHandler Netty Boss #%d").build();
    ThreadFactory workerFactory = new ThreadFactoryBuilder().setNameFormat("ShuffleHandler Netty Worker #%d").build();
    int maximumPoolSize = conf.getInt(MAXIMUM_THREAD_POOL_SIZE, DEFAULT_MAXIMUM_THREAD_POOL_SIZE);
    try {
        workerThreadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(workerFactory);
        workerThreadPool.setMaximumPoolSize(maximumPoolSize);
    } catch (ClassCastException e) {
        LOG.warn("Netty worker thread pool is not of type ThreadPoolExecutor", e);
    }
    LOG.info("Netty starting up with a maximum of " + maximumPoolSize + " worker threads");
    channelFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), workerThreadPool, maximumPoolSize);
}

5. Context#prepare()

Project: apache-storm-test
File: Context.java
/**
     * initialization per Storm configuration 
     */
@SuppressWarnings("rawtypes")
public void prepare(Map storm_conf) {
    this.storm_conf = storm_conf;
    connections = new HashMap<>();
    //each context will have a single client channel factory
    int maxWorkers = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
    ThreadFactory bossFactory = new NettyRenameThreadFactory("client" + "-boss");
    ThreadFactory workerFactory = new NettyRenameThreadFactory("client" + "-worker");
    if (maxWorkers > 0) {
        clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), maxWorkers);
    } else {
        clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory));
    }
    clientScheduleService = new HashedWheelTimer(new NettyRenameThreadFactory("client-schedule-service"));
}

6. SimpleKafkaClient#startUp()

Project: weave
File: SimpleKafkaClient.java
@Override
protected void startUp() throws Exception {
    brokerCache.startAndWait();
    ThreadFactory threadFactory = Threads.createDaemonThreadFactory("kafka-client-netty-%d");
    NioClientBossPool bossPool = new NioClientBossPool(Executors.newSingleThreadExecutor(threadFactory), 1, new HashedWheelTimer(threadFactory), null);
    NioWorkerPool workerPool = new NioWorkerPool(Executors.newFixedThreadPool(4, threadFactory), 4);
    bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(bossPool, workerPool));
    bootstrap.setPipelineFactory(new KafkaChannelPipelineFactory());
    connectionPool = new ConnectionPool(bootstrap);
}

7. ConfigurableThreadFactoryTest#testCustomExceptionHandler()

Project: watchmaker
File: ConfigurableThreadFactoryTest.java
@Test
public void testCustomExceptionHandler() throws InterruptedException {
    ExceptionHandler exceptionHandler = new ExceptionHandler();
    ThreadFactory threadFactory = new ConfigurableThreadFactory("Test", Thread.MAX_PRIORITY, false, exceptionHandler);
    Runnable doNothing = new Runnable() {

        public void run() {
            throw new IllegalStateException("This is a test.");
        }
    };
    Thread thread = threadFactory.newThread(doNothing);
    thread.start();
    thread.join();
    assert exceptionHandler.getExceptionCount() == 1 : "Exception not thrown.";
}

8. ConfigurableThreadFactoryTest#testDefaultExceptionHandler()

Project: watchmaker
File: ConfigurableThreadFactoryTest.java
@Test
public void testDefaultExceptionHandler() throws InterruptedException {
    // Intercept std. err.
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    System.setErr(new PrintStream(byteStream));
    ThreadFactory threadFactory = new ConfigurableThreadFactory("Test", Thread.MAX_PRIORITY, false);
    Runnable doNothing = new Runnable() {

        public void run() {
            throw new IllegalStateException("This is a test.");
        }
    };
    Thread thread = threadFactory.newThread(doNothing);
    thread.start();
    thread.join();
    String output = byteStream.toString();
    assert output.startsWith("java.lang.IllegalStateException") : "Exception handler failed to log exception.";
}

9. ConfigurableThreadFactoryTest#testNonDaemonThreads()

Project: watchmaker
File: ConfigurableThreadFactoryTest.java
@Test
public void testNonDaemonThreads() {
    ThreadFactory threadFactory = new ConfigurableThreadFactory("Test", Thread.MAX_PRIORITY, false);
    Runnable doNothing = new Runnable() {

        public void run() {
        // Do nothing.
        }
    };
    Thread thread = threadFactory.newThread(doNothing);
    assert thread.getName().startsWith("Test") : "Wrong thread name: " + thread.getName();
    assert thread.getPriority() == Thread.MAX_PRIORITY : "Wrong priority: " + thread.getPriority();
    assert !thread.isDaemon() : "Thread should not be a daemon.";
}

10. ConfigurableThreadFactoryTest#testDaemonThreads()

Project: watchmaker
File: ConfigurableThreadFactoryTest.java
@Test
public void testDaemonThreads() {
    ThreadFactory threadFactory = new ConfigurableThreadFactory("Test", Thread.MIN_PRIORITY, true);
    Runnable doNothing = new Runnable() {

        public void run() {
        // Do nothing.
        }
    };
    Thread thread1 = threadFactory.newThread(doNothing);
    assert thread1.getName().startsWith("Test") : "Wrong thread name: " + thread1.getName();
    assert thread1.getPriority() == Thread.MIN_PRIORITY : "Wrong priority: " + thread1.getPriority();
    assert thread1.isDaemon() : "Thread should be a daemon.";
    // Second thread should have a different name.
    Thread thread2 = threadFactory.newThread(doNothing);
    assert thread2.getName().startsWith("Test") : "Wrong thread name: " + thread2.getName();
    assert !thread1.getName().equals(thread2.getName()) : "Thread names should be different.";
}

11. StandbySpanStreamDataSendWorker#start()

Project: pinpoint
File: StandbySpanStreamDataSendWorker.java
public void start() {
    final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true);
    this.workerThread = threadFactory.newThread(this);
    logger.info("start() started.");
    if (!workerThread.isAlive()) {
        this.isStarted = true;
        this.workerThread.start();
        logger.info("start() completed.");
    } else {
        logger.info("start() failed. caused:already started.", this.getClass().getSimpleName());
    }
}

12. BufferedUdpDataSender#startScheduledFlush()

Project: pinpoint
File: BufferedUdpDataSender.java
private Thread startScheduledFlush() {
    final ThreadFactory threadFactory = new PinpointThreadFactory(SCHEDULED_FLUSH, true);
    final Thread thread = threadFactory.newThread(new Runnable() {

        @Override
        public void run() {
            final Thread currentThread = Thread.currentThread();
            while (!currentThread.isInterrupted()) {
                try {
                    chunkHeaderBufferedSerializer.flush();
                } catch (TException e) {
                    logger.warn("Failed to flush. caused={}", e.getMessage(), e);
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException ignored) {
                    currentThread.interrupt();
                }
            }
            logger.info("stop ScheduledFlush {} - {}", currentThread.getName(), currentThread.getId());
        }
    });
    logger.info("stop ScheduledFlush {} - {}", thread.getName(), thread.getId());
    thread.start();
    return thread;
}

13. AutoFlusher#initialize()

Project: pinpoint
File: AutoFlusher.java
public void initialize() {
    if (cachedStatisticsDaoList == null || cachedStatisticsDaoList.isEmpty()) {
        return;
    }
    ThreadFactory threadFactory = PinpointThreadFactory.createThreadFactory(this.getClass().getSimpleName());
    executor = Executors.newScheduledThreadPool(cachedStatisticsDaoList.size(), threadFactory);
    for (CachedStatisticsDao dao : cachedStatisticsDaoList) {
        executor.scheduleAtFixedRate(new Worker(dao), 0L, flushPeriod, TimeUnit.MILLISECONDS);
    }
    logger.info("Auto flusher initialized.");
}

14. DefaultExecutorServiceFactory#getThreadFactory()

Project: pi4j
File: DefaultExecutorServiceFactory.java
/**
     * return an instance to the thread factory used to create new executor services
     */
private static ThreadFactory getThreadFactory(final String nameFormat) {
    final ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
    return new ThreadFactory() {

        final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;

        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = defaultThreadFactory.newThread(runnable);
            if (nameFormat != null) {
                thread.setName(String.format(nameFormat, count.getAndIncrement()));
            }
            return thread;
        }
    };
}

15. ThreadPoolExecutorTest#testGetThreadFactory()

Project: openjdk
File: ThreadPoolExecutorTest.java
/**
     * getThreadFactory returns factory in constructor if not set
     */
public void testGetThreadFactory() {
    ThreadFactory threadFactory = new SimpleThreadFactory();
    final ThreadPoolExecutor p = new ThreadPoolExecutor(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), threadFactory, new NoOpREHandler());
    try (PoolCleaner cleaner = cleaner(p)) {
        assertSame(threadFactory, p.getThreadFactory());
    }
}

16. ThreadPoolExecutorSubclassTest#testGetThreadFactory()

Project: openjdk
File: ThreadPoolExecutorSubclassTest.java
/**
     * getThreadFactory returns factory in constructor if not set
     */
public void testGetThreadFactory() {
    final ThreadFactory threadFactory = new SimpleThreadFactory();
    final ThreadPoolExecutor p = new CustomTPE(1, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), threadFactory, new NoOpREHandler());
    try (PoolCleaner cleaner = cleaner(p)) {
        assertSame(threadFactory, p.getThreadFactory());
    }
}

17. ByteEchoPeerBase#run()

Project: netty
File: ByteEchoPeerBase.java
public void run() throws Exception {
    final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(connectGroup).channelFactory(NioUdtProvider.BYTE_RENDEZVOUS).handler(new ChannelInitializer<UdtChannel>() {

            @Override
            protected void initChannel(UdtChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoPeerHandler(messageSize));
            }
        });
        final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
        future.channel().closeFuture().sync();
    } finally {
        connectGroup.shutdownGracefully();
    }
}

18. UserShardStrategyFactory#getShardAccessStrategy()

Project: mybatis-shards
File: UserShardStrategyFactory.java
private ShardAccessStrategy getShardAccessStrategy() {
    ThreadFactory factory = new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    };
    ThreadPoolExecutor exec = new ThreadPoolExecutor(10, 50, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory);
    return new ParallelShardAccessStrategy(exec);
//		return new SequentialShardAccessStrategy();
}

19. HorizontalShardStrategyFactory#getShardAccessStrategy()

Project: mybatis-shards
File: HorizontalShardStrategyFactory.java
private ShardAccessStrategy getShardAccessStrategy() {
    ThreadFactory factory = new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            return t;
        }
    };
    ThreadPoolExecutor exec = new ThreadPoolExecutor(10, 50, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory);
    return new ParallelShardAccessStrategy(exec);
//		return new SequentialShardAccessStrategy();
}

20. EventServiceImpl#init()

Project: lens
File: EventServiceImpl.java
/*
   * (non-Javadoc)
   *
   * @see org.apache.hive.service.AbstractService#init(org.apache.hadoop.hive.conf.HiveConf)
   */
@Override
public synchronized void init(HiveConf hiveConf) {
    int numProcs = Runtime.getRuntime().availableProcessors();
    ThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("Event_Service_Thread-%d").daemon(false).priority(Thread.NORM_PRIORITY).build();
    eventHandlerPool = Executors.newFixedThreadPool(hiveConf.getInt(LensConfConstants.EVENT_SERVICE_THREAD_POOL_SIZE, numProcs), factory);
    super.init(hiveConf);
}

21. StreamingStateTransfer#createThreadPool()

Project: JGroups
File: StreamingStateTransfer.java
protected ThreadPoolExecutor createThreadPool() {
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(0, max_pool, pool_thread_keep_alive, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
    ThreadFactory factory = new ThreadFactory() {

        private final AtomicInteger thread_id = new AtomicInteger(1);

        public Thread newThread(final Runnable command) {
            return getThreadFactory().newThread(command, "StreamingStateTransfer-sender-" + thread_id.getAndIncrement());
        }
    };
    threadPool.setRejectedExecutionHandler(new ShutdownRejectedExecutionHandler(threadPool.getRejectedExecutionHandler()));
    threadPool.setThreadFactory(factory);
    return threadPool;
}

22. LoadSheddingStreamExecutorServiceFactory#create()

Project: incubator-s4
File: LoadSheddingStreamExecutorServiceFactory.java
@Override
public ExecutorService create(int parallelism, final String name, final ClassLoader classLoader) {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("stream-" + name + "-%d").setThreadFactory(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setContextClassLoader(classLoader);
            return t;
        }
    }).build();
    RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            metrics.droppedEvent(name);
        }
    };
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(parallelism, parallelism, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(workQueueSize), threadFactory, rejectedExecutionHandler);
    tpe.allowCoreThreadTimeOut(true);
    return tpe;
}

23. LoadSheddingSenderExecutorServiceFactory#create()

Project: incubator-s4
File: LoadSheddingSenderExecutorServiceFactory.java
@Override
public ExecutorService create() {
    boolean remote = (this instanceof RemoteSendersExecutorServiceFactory);
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(remote ? "remote-sender-%d" : "sender-%d").build();
    RejectedExecutionHandler rejectedExecutionHandler = (remote ? new RejectedExecutionHandler() {

        // from a remote sender
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            metrics.droppedEventInRemoteSender();
        }
    } : new RejectedExecutionHandler() {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            metrics.droppedEventInSender();
        }
    });
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(parallelism, parallelism, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(workQueueSize), threadFactory, rejectedExecutionHandler);
    tpe.allowCoreThreadTimeOut(true);
    return tpe;
}

24. ProcessingElement#setTimerInterval()

Project: incubator-s4
File: ProcessingElement.java
/**
     * Set a timer that calls {@link #onTime()}.
     * 
     * If {@code interval==0} the timer is disabled.
     * 
     * @param interval
     *            in timeUnit
     * @param timeUnit
     *            the timeUnit of interval
     */
public ProcessingElement setTimerInterval(long interval, TimeUnit timeUnit) {
    timerIntervalInMilliseconds = TimeUnit.MILLISECONDS.convert(interval, timeUnit);
    Preconditions.checkArgument(isPrototype, "This method can only be used on the PE prototype. Trigger not set.");
    if (triggerTimer != null) {
        triggerTimer.shutdownNow();
    }
    if (interval == 0) {
        return this;
    }
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Expection from timer thread", e);
        }
    }).setNameFormat("Timer-" + getClass().getSimpleName()).build();
    triggerTimer = Executors.newSingleThreadScheduledExecutor(threadFactory);
    return this;
}

25. HystrixConcurrencyStrategy#getThreadPool()

Project: Hystrix
File: HystrixConcurrencyStrategy.java
/**
     * Factory method to provide {@link ThreadPoolExecutor} instances as desired.
     * <p>
     * Note that the corePoolSize, maximumPoolSize and keepAliveTime values will be dynamically set during runtime if their values change using the {@link ThreadPoolExecutor#setCorePoolSize},
     * {@link ThreadPoolExecutor#setMaximumPoolSize} and {@link ThreadPoolExecutor#setKeepAliveTime} methods.
     * <p>
     * <b>Default Implementation</b>
     * <p>
     * Implementation using standard java.util.concurrent.ThreadPoolExecutor
     * 
     * @param threadPoolKey
     *            {@link HystrixThreadPoolKey} representing the {@link HystrixThreadPool} that this {@link ThreadPoolExecutor} will be used for.
     * @param corePoolSize
     *            Core number of threads requested via properties (or system default if no properties set).
     * @param maximumPoolSize
     *            Max number of threads requested via properties (or system default if no properties set).
     * @param keepAliveTime
     *            Keep-alive time for threads requested via properties (or system default if no properties set).
     * @param unit
     *            {@link TimeUnit} corresponding with keepAliveTime
     * @param workQueue
     *            {@code BlockingQueue<Runnable>} as provided by {@link #getBlockingQueue(int)}
     * @return instance of {@link ThreadPoolExecutor}
     */
public ThreadPoolExecutor getThreadPool(final HystrixThreadPoolKey threadPoolKey, HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize, HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
    ThreadFactory threadFactory = null;
    if (!PlatformSpecific.isAppEngine()) {
        threadFactory = new ThreadFactory() {

            protected final AtomicInteger threadNumber = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, "hystrix-" + threadPoolKey.name() + "-" + threadNumber.incrementAndGet());
                thread.setDaemon(true);
                return thread;
            }
        };
    } else {
        threadFactory = PlatformSpecific.getAppEngineThreadFactory();
    }
    return new ThreadPoolExecutor(corePoolSize.get(), maximumPoolSize.get(), keepAliveTime.get(), unit, workQueue, threadFactory);
}

26. Threads#newDaemonThreadFactory()

Project: hindex
File: Threads.java
/**
   * Get a named {@link ThreadFactory} that just builds daemon threads
   * @param prefix name prefix for all threads created from the factory
   * @return a thread factory that creates named, daemon threads
   */
public static ThreadFactory newDaemonThreadFactory(final String prefix) {
    final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
    return new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    };
}

27. FastForwardReporter#create()

Project: helios
File: FastForwardReporter.java
public static FastForwardReporter create(MetricRegistry registry, Optional<HostAndPort> address, String metricKey, int intervalSeconds) throws SocketException, UnknownHostException {
    final FastForward ff;
    if (address.isPresent()) {
        ff = FastForward.setup(address.get().getHostText(), address.get().getPort());
    } else {
        ff = FastForward.setup();
    }
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("fast-forward-reporter-%d").build();
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
    return new FastForwardReporter(ff, registry, executorService, metricKey, intervalSeconds, TimeUnit.SECONDS);
}

28. ThreadUtil#getScheduledThreadPoolExecutor()

Project: h-store
File: ThreadUtil.java
/**
     * Have shutdown actually means shutdown. Tasks that need to complete should use
     * futures.
     */
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, UncaughtExceptionHandler handler, int poolSize, int stackSize) {
    // HACK: ScheduledThreadPoolExecutor won't let use the handler so
    // if we're using ExceptionHandlingRunnable then we'll be able to 
    // pick up the exceptions
    Thread.setDefaultUncaughtExceptionHandler(handler);
    ThreadFactory factory = getThreadFactory(name, handler);
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolSize, factory);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    return executor;
}

29. AbstractJerseyService#instrumentedExecutor()

Project: graylog2-server
File: AbstractJerseyService.java
protected ExecutorService instrumentedExecutor(final String executorName, final String threadNameFormat, int poolSize) {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(threadNameFormat).setDaemon(true).build();
    return new InstrumentedExecutorService(Executors.newFixedThreadPool(poolSize, threadFactory), metricRegistry, name(RestApiService.class, executorName));
}

30. ExecutorsUtilsTest#testNewThreadFactory()

Project: gobblin
File: ExecutorsUtilsTest.java
@Test(expectedExceptions = RuntimeException.class)
public void testNewThreadFactory() throws InterruptedException {
    Logger logger = Mockito.mock(Logger.class);
    ThreadFactory threadFactory = ExecutorsUtils.newThreadFactory(Optional.of(logger));
    final RuntimeException runtimeException = new RuntimeException();
    Thread thread = threadFactory.newThread(new Runnable() {

        @Override
        public void run() {
            throw runtimeException;
        }
    });
    thread.setName("foo");
    String errorMessage = String.format("Thread %s threw an uncaught exception: %s", thread, runtimeException);
    Mockito.doThrow(runtimeException).when(logger).error(errorMessage, runtimeException);
    thread.run();
}

31. StreamCommandExecutorProvider#get()

Project: gerrit
File: StreamCommandExecutorProvider.java
@Override
public WorkQueue.Executor get() {
    final WorkQueue.Executor executor;
    executor = queues.createQueue(poolSize, "SSH-Stream-Worker");
    final ThreadFactory parent = executor.getThreadFactory();
    executor.setThreadFactory(new ThreadFactory() {

        @Override
        public Thread newThread(final Runnable task) {
            final Thread t = parent.newThread(task);
            t.setPriority(Thread.MIN_PRIORITY);
            return t;
        }
    });
    return executor;
}

32. ThreadPool#init()

Project: floodlight
File: ThreadPool.java
@Override
public void init(FloodlightModuleContext context) throws FloodlightModuleException {
    final ThreadGroup tg = new ThreadGroup("Scheduled Task Threads");
    ThreadFactory f = new ThreadFactory() {

        AtomicInteger id = new AtomicInteger();

        @Override
        public Thread newThread(Runnable runnable) {
            return new Thread(tg, runnable, "Scheduled-" + id.getAndIncrement());
        }
    };
    executor = Executors.newScheduledThreadPool(5, f);
}

33. DisruptorCommandConsumer#doStart()

Project: es4j
File: DisruptorCommandConsumer.java
@Override
@SuppressWarnings("unchecked")
protected void doStart() {
    log.info("Starting command consumer");
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("eventsourcing-%d").setDaemon(true).build();
    disruptor = new Disruptor<>(() -> new CommandEvent(commandClasses), RING_BUFFER_SIZE, threadFactory);
    disruptor.setDefaultExceptionHandler(new CommandEventExceptionHandler());
    disruptor.handleEventsWith(this::timestamp).thenHandleEventsWithWorkerPool(this::journal).thenHandleEventsWithWorkerPool(this::complete);
    ringBuffer = disruptor.start();
    notifyStarted();
}

34. Client#getPoolFromNs()

Project: dynamodb-titan-storage-backend
File: Client.java
public static final ThreadPoolExecutor getPoolFromNs(Configuration ns) {
    final int maxQueueSize = ns.get(Constants.DYNAMODB_CLIENT_EXECUTOR_QUEUE_MAX_LENGTH);
    final ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("delegate-%d").build();
    //begin adaptation of constructor at
    //https://github.com/buka/titan/blob/master/src/main/java/com/thinkaurelius/titan/diskstorage/dynamodb/DynamoDBClient.java#L104
    final int maxPoolSize = ns.get(Constants.DYNAMODB_CLIENT_EXECUTOR_MAX_POOL_SIZE);
    final int corePoolSize = ns.get(Constants.DYNAMODB_CLIENT_EXECUTOR_CORE_POOL_SIZE);
    final long keepAlive = ns.get(Constants.DYNAMODB_CLIENT_EXECUTOR_KEEP_ALIVE);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAlive, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(maxQueueSize), factory, new ThreadPoolExecutor.CallerRunsPolicy());
    //end adaptation of constructor at
    //https://github.com/buka/titan/blob/master/src/main/java/com/thinkaurelius/titan/diskstorage/dynamodb/DynamoDBClient.java#L104
    executor.allowCoreThreadTimeOut(false);
    executor.prestartAllCoreThreads();
    return executor;
}

35. LifecycleEnvironmentTest#executorServiceThreadFactory()

Project: dropwizard
File: LifecycleEnvironmentTest.java
@Test
public void executorServiceThreadFactory() throws ExecutionException, InterruptedException {
    final String expectedName = "DropWizard ThreadFactory Test";
    final String expectedNamePattern = expectedName + "-%d";
    final ThreadFactory tfactory = (new ThreadFactoryBuilder()).setDaemon(false).setNameFormat(expectedNamePattern).build();
    final ExecutorService executorService = environment.executorService("Dropwizard Service", tfactory).build();
    final Future<Boolean> isFactoryInUse = executorService.submit(() -> Thread.currentThread().getName().startsWith(expectedName));
    assertThat(isFactoryInUse.get()).isTrue();
}

36. LifecycleEnvironmentTest#scheduledExecutorServiceThreadFactory()

Project: dropwizard
File: LifecycleEnvironmentTest.java
@Test
public void scheduledExecutorServiceThreadFactory() throws ExecutionException, InterruptedException {
    final String expectedName = "DropWizard ThreadFactory Test";
    final String expectedNamePattern = expectedName + "-%d";
    final ThreadFactory tfactory = (new ThreadFactoryBuilder()).setDaemon(false).setNameFormat(expectedNamePattern).build();
    final ScheduledExecutorService executorService = environment.scheduledExecutorService("DropWizard Service", tfactory).build();
    final Future<Boolean> isFactoryInUse = executorService.submit(() -> Thread.currentThread().getName().startsWith(expectedName));
    assertThat(isFactoryInUse.get()).isTrue();
}

37. MemoryLeakTest#beforeMemoryLeakTest()

Project: concurrentlinkedhashmap
File: MemoryLeakTest.java
@BeforeMethod
public void beforeMemoryLeakTest() {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setPriority(Thread.MAX_PRIORITY).setDaemon(true).build();
    statusExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
    statusExecutor.scheduleAtFixedRate(newStatusTask(), statusInterval, statusInterval, SECONDS);
    map = new Builder<Long, Long>().maximumWeightedCapacity(threads).build();
}

38. BasicThreadFactoryTest#testNewThreadNoExHandler()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the original exception hander is not touched if none is
     * specified.
     */
@Test
public void testNewThreadNoExHandler() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final Thread.UncaughtExceptionHandler handler = EasyMock.createMock(Thread.UncaughtExceptionHandler.class);
    final Thread t = new Thread();
    t.setUncaughtExceptionHandler(handler);
    EasyMock.expect(wrapped.newThread(r)).andReturn(t);
    EasyMock.replay(wrapped, r, handler);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
    assertSame("Wrong thread", t, factory.newThread(r));
    assertEquals("Wrong exception handler", handler, t.getUncaughtExceptionHandler());
    EasyMock.verify(wrapped, r, handler);
}

39. BasicThreadFactoryTest#testNewThreadExHandler()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the exception handler is set if one is provided.
     */
@Test
public void testNewThreadExHandler() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final Thread.UncaughtExceptionHandler handler = EasyMock.createMock(Thread.UncaughtExceptionHandler.class);
    final Thread t = new Thread();
    EasyMock.expect(wrapped.newThread(r)).andReturn(t);
    EasyMock.replay(wrapped, r, handler);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).uncaughtExceptionHandler(handler).build();
    assertSame("Wrong thread", t, factory.newThread(r));
    assertEquals("Wrong exception handler", handler, t.getUncaughtExceptionHandler());
    EasyMock.verify(wrapped, r, handler);
}

40. BasicThreadFactoryTest#testNewThreadNoPriority()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the original priority is not changed if no priority is
     * specified.
     */
@Test
public void testNewThreadNoPriority() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final int orgPriority = Thread.NORM_PRIORITY + 1;
    final Thread t = new Thread();
    t.setPriority(orgPriority);
    EasyMock.expect(wrapped.newThread(r)).andReturn(t);
    EasyMock.replay(wrapped, r);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
    assertSame("Wrong thread", t, factory.newThread(r));
    assertEquals("Wrong priority", orgPriority, t.getPriority());
    EasyMock.verify(wrapped, r);
}

41. BasicThreadFactoryTest#testNewThreadPriority()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the priority is set on newly created threads.
     */
@Test
public void testNewThreadPriority() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final Thread t = new Thread();
    EasyMock.expect(wrapped.newThread(r)).andReturn(t);
    EasyMock.replay(wrapped, r);
    final int priority = Thread.NORM_PRIORITY + 1;
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).priority(priority).build();
    assertSame("Wrong thread", t, factory.newThread(r));
    assertEquals("Wrong priority", priority, t.getPriority());
    EasyMock.verify(wrapped, r);
}

42. BasicThreadFactoryTest#testNewThreadNoDaemonFlag()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the daemon flag is not touched on newly created threads if
     * it is not specified.
     */
@Test
public void testNewThreadNoDaemonFlag() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r1 = EasyMock.createMock(Runnable.class);
    final Runnable r2 = EasyMock.createMock(Runnable.class);
    final Thread t1 = new Thread();
    final Thread t2 = new Thread();
    t1.setDaemon(true);
    EasyMock.expect(wrapped.newThread(r1)).andReturn(t1);
    EasyMock.expect(wrapped.newThread(r2)).andReturn(t2);
    EasyMock.replay(wrapped, r1, r2);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
    assertSame("Wrong thread 1", t1, factory.newThread(r1));
    assertTrue("No daemon thread", t1.isDaemon());
    assertSame("Wrong thread 2", t2, factory.newThread(r2));
    assertFalse("A daemon thread", t2.isDaemon());
    EasyMock.verify(wrapped, r1, r2);
}

43. BasicThreadFactoryTest#checkDaemonFlag()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Helper method for testing whether the daemon flag is taken into account.
     *
     * @param flag the value of the flag
     */
private void checkDaemonFlag(final boolean flag) {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final Thread t = new Thread();
    EasyMock.expect(wrapped.newThread(r)).andReturn(t);
    EasyMock.replay(wrapped, r);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).daemon(flag).build();
    assertSame("Wrong thread", t, factory.newThread(r));
    assertTrue("Wrong daemon flag", flag == t.isDaemon());
    EasyMock.verify(wrapped, r);
}

44. BasicThreadFactoryTest#testNewThreadNoNamingPattern()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the thread name is not modified if no naming pattern is
     * set.
     */
@Test
public void testNewThreadNoNamingPattern() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final String name = "unchangedThreadName";
    final Thread t = new Thread(name);
    EasyMock.expect(wrapped.newThread(r)).andReturn(t);
    EasyMock.replay(wrapped, r);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
    assertSame("Wrong thread", t, factory.newThread(r));
    assertEquals("Name was changed", name, t.getName());
    EasyMock.verify(wrapped, r);
}

45. BasicThreadFactoryTest#testNewThreadNamingPattern()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests whether the naming pattern is applied to new threads.
     */
@Test
public void testNewThreadNamingPattern() {
    final ThreadFactory wrapped = EasyMock.createMock(ThreadFactory.class);
    final Runnable r = EasyMock.createMock(Runnable.class);
    final int count = 12;
    for (int i = 0; i < count; i++) {
        EasyMock.expect(wrapped.newThread(r)).andReturn(new Thread());
    }
    EasyMock.replay(wrapped, r);
    final BasicThreadFactory factory = builder.wrappedFactory(wrapped).namingPattern(PATTERN).build();
    for (int i = 0; i < count; i++) {
        final Thread t = factory.newThread(r);
        assertEquals("Wrong thread name", String.format(PATTERN, Long.valueOf(i + 1)), t.getName());
        assertEquals("Wrong thread count", i + 1, factory.getThreadCount());
    }
    EasyMock.verify(wrapped, r);
}

46. BasicThreadFactoryTest#testBuilderReset()

Project: commons-lang
File: BasicThreadFactoryTest.java
/**
     * Tests the reset() method of the builder.
     */
@Test
public void testBuilderReset() {
    final ThreadFactory wrappedFactory = EasyMock.createMock(ThreadFactory.class);
    final Thread.UncaughtExceptionHandler exHandler = EasyMock.createMock(Thread.UncaughtExceptionHandler.class);
    EasyMock.replay(wrappedFactory, exHandler);
    builder.namingPattern(PATTERN).daemon(true).priority(Thread.MAX_PRIORITY).uncaughtExceptionHandler(exHandler).wrappedFactory(wrappedFactory);
    builder.reset();
    final BasicThreadFactory factory = builder.build();
    checkFactoryDefaults(factory);
    assertNotSame("Wrapped factory not reset", wrappedFactory, factory.getWrappedFactory());
    EasyMock.verify(wrappedFactory, exHandler);
}

47. CobarSqlMapClientTemplate#createCustomExecutorService()

Project: cobarclient
File: CobarSqlMapClientTemplate.java
private ExecutorService createCustomExecutorService(int poolSize, final String method) {
    int coreSize = Runtime.getRuntime().availableProcessors();
    if (poolSize < coreSize) {
        coreSize = poolSize;
    }
    ThreadFactory tf = new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "thread created at CobarSqlMapClientTemplate method [" + method + "]");
            t.setDaemon(true);
            return t;
        }
    };
    BlockingQueue<Runnable> queueToUse = new LinkedBlockingQueue<Runnable>(coreSize);
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, poolSize, 60, TimeUnit.SECONDS, queueToUse, tf, new ThreadPoolExecutor.CallerRunsPolicy());
    return executor;
}

48. ExecutorThreadPool#createThreadPoolExecutor()

Project: cdap
File: ExecutorThreadPool.java
private ThreadPoolExecutor createThreadPoolExecutor() {
    ThreadFactory threadFactory = new ThreadFactory() {

        private final ThreadGroup threadGroup = new ThreadGroup("scheduler-thread");

        private final AtomicLong count = new AtomicLong(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(threadGroup, r, String.format("scheduler-executor-%d", count.getAndIncrement()));
            t.setDaemon(true);
            return t;
        }
    };
    return new ThreadPoolExecutor(0, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory, new ThreadPoolExecutor.AbortPolicy());
}

49. NettyComponent#createExecutorService()

Project: camel
File: NettyComponent.java
protected OrderedMemoryAwareThreadPoolExecutor createExecutorService() {
    // use ordered thread pool, to ensure we process the events in order, and can send back
    // replies in the expected order. eg this is required by TCP.
    // and use a Camel thread factory so we have consistent thread namings
    // we should use a shared thread pool as recommended by Netty
    // NOTE: if we don't specify the MaxChannelMemorySize and MaxTotalMemorySize, the thread pool
    // could eat up all the heap memory when the tasks are added very fast
    String pattern = getCamelContext().getExecutorServiceManager().getThreadNamePattern();
    ThreadFactory factory = new CamelThreadFactory(pattern, "NettyOrderedWorker", true);
    return new OrderedMemoryAwareThreadPoolExecutor(getMaximumPoolSize(), configuration.getMaxChannelMemorySize(), configuration.getMaxTotalMemorySize(), 30, TimeUnit.SECONDS, factory);
}

50. DefaultExecutorServiceManager#newThreadPool()

Project: camel
File: DefaultExecutorServiceManager.java
@Override
public ExecutorService newThreadPool(Object source, String name, ThreadPoolProfile profile) {
    String sanitizedName = URISupport.sanitizeUri(name);
    ObjectHelper.notNull(profile, "ThreadPoolProfile");
    ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile();
    profile.addDefaults(defaultProfile);
    ThreadFactory threadFactory = createThreadFactory(sanitizedName, true);
    ExecutorService executorService = threadPoolFactory.newThreadPool(profile, threadFactory);
    onThreadPoolCreated(executorService, source, profile.getId());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Created new ThreadPool for source: {} with name: {}. -> {}", source, sanitizedName, executorService);
    }
    return executorService;
}

51. TransferManagerUtils#createDefaultExecutorService()

Project: aws-sdk-java
File: TransferManagerUtils.java
/**
     * Returns a new thread pool configured with the default settings.
     *
     * @return A new thread pool configured with the default settings.
     */
public static ThreadPoolExecutor createDefaultExecutorService() {
    ThreadFactory threadFactory = new ThreadFactory() {

        private int threadCount = 1;

        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("s3-transfer-manager-worker-" + threadCount++);
            return thread;
        }
    };
    return (ThreadPoolExecutor) Executors.newFixedThreadPool(10, threadFactory);
}

52. ProducerClient#connect()

Project: aws-big-data-blog
File: ProducerClient.java
/**
	 * {@inheritDoc} 
	 */
public void connect() {
    if (!canRun.compareAndSet(true, false)) {
        throw new IllegalStateException("Already running");
    }
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    executorService = Executors.newFixedThreadPool(threads, threadFactory);
    for (int i = 0; i < this.threads; i++) {
        ProducerBase p = new ProducerBase(this.eventsQueue, this.kinesisClient, this.streamName);
        executorService.execute(p);
        logger.info(name + ": New thread started : {}", p);
    }
}

53. PTExecutors#newThreadFactory()

Project: atlasdb
File: PTExecutors.java
public static ThreadFactory newThreadFactory(final String prefix, final int priority, final boolean isDaemon) {
    ThreadFactory threadFactory = new ThreadFactory() {

        private final AtomicInteger nextThreadId = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, prefix + "-" + nextThreadId.getAndIncrement());
            t.setPriority(priority);
            t.setDaemon(isDaemon);
            return t;
        }
    };
    return threadFactory;
}

54. ExecutionTask#createJobflowExecutor()

Project: asakusafw
File: ExecutionTask.java
private ExecutorService createJobflowExecutor(final String batchId) {
    assert batchId != null;
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(MessageFormat.format("JobflowExecutor-{0}", batchId));
            thread.setDaemon(true);
            return thread;
        }
    };
    if (serializeFlows) {
        return Executors.newFixedThreadPool(1, threadFactory);
    } else {
        return Executors.newCachedThreadPool(threadFactory);
    }
}

55. TelemetryClient#configThreadPool()

Project: ApplicationInsights-Android
File: TelemetryClient.java
private void configThreadPool() {
    int corePoolSize = 5;
    int maxPoolSize = 10;
    int queueSize = 5;
    long timeout = 1;
    ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(queueSize);
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(false);
            return thread;
        }
    };
    RejectedExecutionHandler handler = new RejectedExecutionHandler() {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            InternalLogging.error(TAG, "too many track() calls at a time");
        }
    };
    threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, timeout, TimeUnit.SECONDS, queue, threadFactory, handler);
}

56. SafeKeeper#init()

Project: incubator-s4
File: SafeKeeper.java
@Inject
private void init() {
    // NOTE: those thread pools should be fine tuned according to backend and application load/requirements.
    // For now:
    // - number of threads and work queue size have overridable defaults
    // - failures are logged
    // - when storage queue is full, we throttle backwards to the serialization threadpool
    // - when serialization queue is full, we abort execution for new entries
    // - fetching uses a synchronous queue and therefore is a blocking operation, with a timeout
    ThreadFactory storageThreadFactory = new ThreadFactoryBuilder().setNameFormat("Checkpointing-storage-%d").setUncaughtExceptionHandler(new UncaughtExceptionLogger("storage")).build();
    storageThreadPool = new ThreadPoolExecutor(1, storageMaxThreads, storageThreadKeepAliveSeconds, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(storageMaxOutstandingRequests), storageThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    storageThreadPool.allowCoreThreadTimeOut(true);
    ThreadFactory serializationThreadFactory = new ThreadFactoryBuilder().setNameFormat("Checkpointing-serialization-%d").setUncaughtExceptionHandler(new UncaughtExceptionLogger("serialization")).build();
    serializationThreadPool = new ThreadPoolExecutor(1, serializationMaxThreads, serializationThreadKeepAliveSeconds, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(serializationMaxOutstandingRequests), serializationThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    serializationThreadPool.allowCoreThreadTimeOut(true);
    ThreadFactory fetchingThreadFactory = new ThreadFactoryBuilder().setNameFormat("Checkpointing-fetching-%d").setUncaughtExceptionHandler(new UncaughtExceptionLogger("fetching")).build();
    fetchingThreadPool = new ThreadPoolExecutor(0, fetchingMaxThreads, fetchingThreadKeepAliveSeconds, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(fetchingQueueSize), fetchingThreadFactory);
    fetchingThreadPool.allowCoreThreadTimeOut(true);
}

57. ThreadBridgeTest#test()

Project: ReactFX
File: ThreadBridgeTest.java
@Test
public void test() throws InterruptedException, ExecutionException {
    ThreadFactory threadFactory1 =  runnable -> new Thread(runnable, "thread 1");
    ThreadFactory threadFactory2 =  runnable -> new Thread(runnable, "thread 2");
    ExecutorService exec1 = Executors.newSingleThreadExecutor(threadFactory1);
    ExecutorService exec2 = Executors.newSingleThreadExecutor(threadFactory2);
    EventSource<Integer> src1 = new EventSource<>();
    EventStream<Integer> stream2 = src1.threadBridge(exec1, exec2);
    EventStream<Integer> stream1 = stream2.threadBridge(exec2, exec1);
    List<Integer> emittedFrom2 = new ArrayList<>();
    List<Integer> emittedFrom1 = new ArrayList<>();
    List<String> emissionThreads2 = new ArrayList<>();
    List<String> emissionThreads1 = new ArrayList<>();
    CompletableFuture<List<Integer>> emittedFrom2Final = new CompletableFuture<>();
    CompletableFuture<List<Integer>> emittedFrom1Final = new CompletableFuture<>();
    CompletableFuture<List<String>> emissionThreads2Final = new CompletableFuture<>();
    CompletableFuture<List<String>> emissionThreads1Final = new CompletableFuture<>();
    CountDownLatch subscribed = new CountDownLatch(2);
    exec2.execute(() -> {
        stream2.subscribe( i -> {
            if (i != null) {
                emittedFrom2.add(i);
                emissionThreads2.add(Thread.currentThread().getName());
            } else {
                emittedFrom2Final.complete(emittedFrom2);
                emissionThreads2Final.complete(emissionThreads2);
            }
        });
        subscribed.countDown();
    });
    exec1.execute(() -> {
        stream1.subscribe( i -> {
            if (i != null) {
                emittedFrom1.add(i);
                emissionThreads1.add(Thread.currentThread().getName());
            } else {
                emittedFrom1Final.complete(emittedFrom1);
                emissionThreads1Final.complete(emissionThreads1);
            }
        });
        subscribed.countDown();
    });
    subscribed.await();
    exec1.execute(() -> {
        src1.push(1);
        src1.push(2);
        src1.push(3);
        src1.push(null);
    });
    assertEquals(Arrays.asList(1, 2, 3), emittedFrom2Final.get());
    assertEquals(Arrays.asList(1, 2, 3), emittedFrom1Final.get());
    assertEquals(Arrays.asList("thread 2", "thread 2", "thread 2"), emissionThreads2Final.get());
    assertEquals(Arrays.asList("thread 1", "thread 1", "thread 1"), emissionThreads1Final.get());
    exec1.shutdown();
    exec2.shutdown();
}

58. Throws#realMain()

Project: openjdk
File: Throws.java
private static void realMain(String[] args) throws Throwable {
    final ThreadFactory fac = defaultThreadFactory();
    final ThreadFactory nullFactory = null;
    final RejectedExecutionHandler reh = new RejectedExecutionHandler() {

        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        }
    };
    final RejectedExecutionHandler nullHandler = null;
    THROWS(NullPointerException.class, () -> newFixedThreadPool(3, null), () -> newCachedThreadPool(null), () -> newSingleThreadScheduledExecutor(null), () -> newScheduledThreadPool(0, null), () -> unconfigurableExecutorService(null), () -> unconfigurableScheduledExecutorService(null), () -> callable(null, "foo"), () -> callable((Runnable) null), () -> callable((PrivilegedAction<?>) null), () -> callable((PrivilegedExceptionAction<?>) null), () -> privilegedCallable((Callable<?>) null), () -> new ScheduledThreadPoolExecutor(0, nullFactory), () -> new ScheduledThreadPoolExecutor(0, nullFactory, reh), () -> new ScheduledThreadPoolExecutor(0, fac, nullHandler));
    THROWS(IllegalArgumentException.class, () -> newFixedThreadPool(-42), () -> newFixedThreadPool(0), () -> newFixedThreadPool(-42, fac), () -> newFixedThreadPool(0, fac), () -> newScheduledThreadPool(-42), () -> new ScheduledThreadPoolExecutor(-42), () -> new ScheduledThreadPoolExecutor(-42, reh), () -> new ScheduledThreadPoolExecutor(-42, fac, reh));
    try {
        newFixedThreadPool(1).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newFixedThreadPool(1, fac).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newSingleThreadExecutor().shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newCachedThreadPool().shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newSingleThreadScheduledExecutor().shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newSingleThreadScheduledExecutor(fac).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newScheduledThreadPool(0).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        newScheduledThreadPool(0, fac).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        new ScheduledThreadPoolExecutor(0).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        new ScheduledThreadPoolExecutor(0, fac).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
    try {
        new ScheduledThreadPoolExecutor(0, fac, reh).shutdownNow();
        pass();
    } catch (Throwable t) {
        unexpected(t);
    }
}

59. MsgEchoServer#main()

Project: netty
File: MsgEchoServer.java
public static void main(String[] args) throws Exception {
    final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER);
    // Configure the server.
    try {
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR).option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<UdtChannel>() {

            @Override
            public void initChannel(final UdtChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoServerHandler());
            }
        });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

60. ByteEchoServer#main()

Project: netty
File: ByteEchoServer.java
public static void main(String[] args) throws Exception {
    final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER);
    // Configure the server.
    try {
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR).option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<UdtChannel>() {

            @Override
            public void initChannel(final UdtChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoServerHandler());
            }
        });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

61. EtiaoJobBean#getThread()

Project: incubator-quarks
File: EtiaoJobBean.java
private Thread getThread(Runnable r) {
    ThreadFactory threads = Executors.defaultThreadFactory();
    return threads.newThread(r);
}

62. ThreadFactoryBuilderTest#testBuildMutateBuild()

Project: guava
File: ThreadFactoryBuilderTest.java
public void testBuildMutateBuild() {
    ThreadFactory factory1 = builder.setPriority(1).build();
    assertEquals(1, factory1.newThread(monitoredRunnable).getPriority());
    ThreadFactory factory2 = builder.setPriority(2).build();
    assertEquals(1, factory1.newThread(monitoredRunnable).getPriority());
    assertEquals(2, factory2.newThread(monitoredRunnable).getPriority());
}

63. ThreadFactoryBuilderTest#testThreadFactoryBuilder_defaults()

Project: guava
File: ThreadFactoryBuilderTest.java
public void testThreadFactoryBuilder_defaults() throws InterruptedException {
    ThreadFactory threadFactory = builder.build();
    Thread thread = threadFactory.newThread(monitoredRunnable);
    checkThreadPoolName(thread, 1);
    Thread defaultThread = Executors.defaultThreadFactory().newThread(monitoredRunnable);
    assertEquals(defaultThread.isDaemon(), thread.isDaemon());
    assertEquals(defaultThread.getPriority(), thread.getPriority());
    assertSame(defaultThread.getThreadGroup(), thread.getThreadGroup());
    assertSame(defaultThread.getUncaughtExceptionHandler(), thread.getUncaughtExceptionHandler());
    assertFalse(completed);
    thread.start();
    thread.join();
    assertTrue(completed);
    // Creating a new thread from the same ThreadFactory will have the same
    // pool ID but a thread ID of 2.
    Thread thread2 = threadFactory.newThread(monitoredRunnable);
    checkThreadPoolName(thread2, 2);
    assertEquals(thread.getName().substring(0, thread.getName().lastIndexOf('-')), thread2.getName().substring(0, thread.getName().lastIndexOf('-')));
    // Building again should give us a different pool ID.
    ThreadFactory threadFactory2 = builder.build();
    Thread thread3 = threadFactory2.newThread(monitoredRunnable);
    checkThreadPoolName(thread3, 1);
    assertThat(thread2.getName().substring(0, thread.getName().lastIndexOf('-'))).isNotEqualTo(thread3.getName().substring(0, thread.getName().lastIndexOf('-')));
}

64. RPCService#run()

Project: floodlight
File: RPCService.java
// *************
// public methods
// *************
/**
     * Start the RPC service
     */
public void run() {
    started = true;
    final ThreadGroup tg1 = new ThreadGroup("Sync Message Handlers");
    tg1.setMaxPriority(Thread.NORM_PRIORITY - 3);
    ThreadFactory f1 = new ThreadFactory() {

        AtomicInteger id = new AtomicInteger();

        @Override
        public Thread newThread(Runnable runnable) {
            return new Thread(tg1, runnable, "SyncMessage-" + id.getAndIncrement());
        }
    };
    syncExecutor = Executors.newCachedThreadPool(f1);
    for (int i = 0; i < SYNC_MESSAGE_POOL; i++) {
        syncExecutor.execute(new SyncMessageWorker());
    }
    final ThreadGroup tg2 = new ThreadGroup("Sync I/O Threads");
    tg2.setMaxPriority(Thread.NORM_PRIORITY - 1);
    ThreadFactory f2 = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable runnable) {
            return new Thread(tg2, runnable);
        }
    };
    bossGroup = new NioEventLoopGroup(0, f2);
    workerGroup = new NioEventLoopGroup(0, f2);
    channelInitializer = new RPCChannelInitializer(syncManager, this, timer);
    startServer(channelInitializer);
    startClients(channelInitializer);
}

65. NettyTransport#createServerBootstrap()

Project: elasticsearch
File: NettyTransport.java
private void createServerBootstrap(String name, Settings settings) {
    boolean blockingServer = TCP_BLOCKING_SERVER.get(settings);
    String port = settings.get("port");
    String bindHost = settings.get("bind_host");
    String publishHost = settings.get("publish_host");
    String tcpNoDelay = settings.get("tcp_no_delay");
    String tcpKeepAlive = settings.get("tcp_keep_alive");
    boolean reuseAddress = settings.getAsBoolean("reuse_address", NetworkUtils.defaultReuseAddress());
    ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings);
    ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings);
    if (logger.isDebugEnabled()) {
        logger.debug("using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], " + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]", name, workerCount, port, bindHost, publishHost, compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax);
    }
    final ThreadFactory bossFactory = daemonThreadFactory(this.settings, HTTP_SERVER_BOSS_THREAD_NAME_PREFIX, name);
    final ThreadFactory workerFactory = daemonThreadFactory(this.settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX, name);
    ServerBootstrap serverBootstrap;
    if (blockingServer) {
        serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory)));
    } else {
        serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), workerCount));
    }
    serverBootstrap.setPipelineFactory(configureServerChannelPipelineFactory(name, settings));
    if (!"default".equals(tcpNoDelay)) {
        serverBootstrap.setOption("child.tcpNoDelay", Booleans.parseBoolean(tcpNoDelay, null));
    }
    if (!"default".equals(tcpKeepAlive)) {
        serverBootstrap.setOption("child.keepAlive", Booleans.parseBoolean(tcpKeepAlive, null));
    }
    if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes());
    }
    if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes());
    }
    serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
    serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
    serverBootstrap.setOption("reuseAddress", reuseAddress);
    serverBootstrap.setOption("child.reuseAddress", reuseAddress);
    serverBootstraps.put(name, serverBootstrap);
}

66. NettyTransport#createServerBootstrap()

Project: elassandra
File: NettyTransport.java
private void createServerBootstrap(String name, Settings settings) {
    boolean blockingServer = settings.getAsBoolean("transport.tcp.blocking_server", this.settings.getAsBoolean(TCP_BLOCKING_SERVER, this.settings.getAsBoolean(TCP_BLOCKING, false)));
    String port = settings.get("port");
    String bindHost = settings.get("bind_host");
    String publishHost = settings.get("publish_host");
    String tcpNoDelay = settings.get("tcp_no_delay");
    String tcpKeepAlive = settings.get("tcp_keep_alive");
    boolean reuseAddress = settings.getAsBoolean("reuse_address", NetworkUtils.defaultReuseAddress());
    ByteSizeValue tcpSendBufferSize = settings.getAsBytesSize("tcp_send_buffer_size", TCP_DEFAULT_SEND_BUFFER_SIZE);
    ByteSizeValue tcpReceiveBufferSize = settings.getAsBytesSize("tcp_receive_buffer_size", TCP_DEFAULT_RECEIVE_BUFFER_SIZE);
    logger.debug("using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]", name, workerCount, port, bindHost, publishHost, compress, connectTimeout, connectionsPerNodeRecovery, connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing, receivePredictorMin, receivePredictorMax);
    final ThreadFactory bossFactory = daemonThreadFactory(this.settings, HTTP_SERVER_BOSS_THREAD_NAME_PREFIX, name);
    final ThreadFactory workerFactory = daemonThreadFactory(this.settings, HTTP_SERVER_WORKER_THREAD_NAME_PREFIX, name);
    ServerBootstrap serverBootstrap;
    if (blockingServer) {
        serverBootstrap = new ServerBootstrap(new OioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory)));
    } else {
        serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), workerCount));
    }
    serverBootstrap.setPipelineFactory(configureServerChannelPipelineFactory(name, settings));
    if (!"default".equals(tcpNoDelay)) {
        serverBootstrap.setOption("child.tcpNoDelay", Booleans.parseBoolean(tcpNoDelay, null));
    }
    if (!"default".equals(tcpKeepAlive)) {
        serverBootstrap.setOption("child.keepAlive", Booleans.parseBoolean(tcpKeepAlive, null));
    }
    if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.setOption("child.sendBufferSize", tcpSendBufferSize.bytes());
    }
    if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.setOption("child.receiveBufferSize", tcpReceiveBufferSize.bytes());
    }
    serverBootstrap.setOption("receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
    serverBootstrap.setOption("child.receiveBufferSizePredictorFactory", receiveBufferSizePredictorFactory);
    serverBootstrap.setOption("reuseAddress", reuseAddress);
    serverBootstrap.setOption("child.reuseAddress", reuseAddress);
    serverBootstraps.put(name, serverBootstrap);
}

67. DefaultExecutorServiceManager#newThread()

Project: camel
File: DefaultExecutorServiceManager.java
@Override
public Thread newThread(String name, Runnable runnable) {
    ThreadFactory factory = createThreadFactory(name, true);
    return factory.newThread(runnable);
}

68. ThreadFactoryBuilder#build()

Project: voltdb
File: ThreadFactoryBuilder.java
private static ThreadFactory build(ThreadFactoryBuilder builder) {
    final String nameFormat = builder.nameFormat;
    final Boolean daemon = builder.daemon;
    final Integer priority = builder.priority;
    final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler;
    final ThreadFactory backingThreadFactory = (builder.backingThreadFactory != null) ? builder.backingThreadFactory : Executors.defaultThreadFactory();
    final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
    return new ThreadFactory() {

        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = backingThreadFactory.newThread(runnable);
            if (nameFormat != null) {
                thread.setName(format(nameFormat, count.getAndIncrement()));
            }
            if (daemon != null) {
                thread.setDaemon(daemon);
            }
            if (priority != null) {
                thread.setPriority(priority);
            }
            if (uncaughtExceptionHandler != null) {
                thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
            }
            return thread;
        }
    };
}

69. SnapshotUtil#requestSnapshot()

Project: voltdb
File: SnapshotUtil.java
/**
     * Request a new snapshot. It will retry for a couple of times. If it
     * doesn't succeed in the specified time, an error response will be sent to
     * the response handler, otherwise a success response will be passed to the
     * handler.
     *
     * The request process runs in a separate thread, this method call will
     * return immediately.
     *
     * @param clientHandle
     * @param path
     * @param nonce
     * @param blocking
     * @param format
     * @param data Any data that needs to be passed to the snapshot target
     * @param handler
     */
public static void requestSnapshot(final long clientHandle, final String path, final String nonce, final boolean blocking, final SnapshotFormat format, final String data, final SnapshotResponseHandler handler, final boolean notifyChanges) {
    final SnapshotInitiationInfo snapInfo = new SnapshotInitiationInfo(path, nonce, blocking, format, data);
    final SimpleClientResponseAdapter adapter = new SimpleClientResponseAdapter(ClientInterface.SNAPSHOT_UTIL_CID, "SnapshotUtilAdapter", true);
    final LinkedBlockingQueue<ClientResponse> responses = new LinkedBlockingQueue<ClientResponse>();
    adapter.registerCallback(clientHandle, new SimpleClientResponseAdapter.Callback() {

        @Override
        public void handleResponse(ClientResponse response) {
            responses.offer(response);
        }
    });
    final SnapshotDaemon sd = VoltDB.instance().getClientInterface().getSnapshotDaemon();
    Runnable work = new Runnable() {

        @Override
        public void run() {
            ClientResponse response = null;
            // abort if unable to succeed in 2 hours
            final long startTime = System.currentTimeMillis();
            boolean hasRequested = false;
            while (System.currentTimeMillis() - startTime <= TimeUnit.HOURS.toMillis(2)) {
                try {
                    if (!hasRequested) {
                        sd.createAndWatchRequestNode(clientHandle, adapter, snapInfo, notifyChanges);
                        hasRequested = true;
                    }
                    try {
                        response = responses.poll(TimeUnit.HOURS.toMillis(2) - (System.currentTimeMillis() - startTime), TimeUnit.MILLISECONDS);
                        if (response == null)
                            break;
                    } catch (InterruptedException e) {
                        VoltDB.crashLocalVoltDB("Should never happen", true, e);
                    }
                    VoltTable[] results = response.getResults();
                    if (response.getStatus() != ClientResponse.SUCCESS) {
                        break;
                    } else if (isSnapshotInProgress(results)) {
                        // retry after a second
                        Thread.sleep(1000);
                        // Request again
                        hasRequested = false;
                        continue;
                    } else if (isSnapshotQueued(results) && notifyChanges) {
                        //Wait for an update on the queued state via ZK
                        continue;
                    } else {
                        // other errors are not recoverable
                        break;
                    }
                } catch (ForwardClientException e) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e1) {
                    }
                    new VoltLogger("SNAPSHOT").warn("Partition detection was unable to submit a snapshot request" + "because one already existed. Retrying.");
                    continue;
                } catch (InterruptedException ignore) {
                }
            }
            handler.handleResponse(response);
        }
    };
    // Use an executor service here to avoid explosion of threads???
    ThreadFactory factory = CoreUtils.getThreadFactory("Snapshot Request - " + nonce);
    Thread workThread = factory.newThread(work);
    workThread.start();
}

70. TezContainerLauncherImpl#start()

Project: tez
File: TezContainerLauncherImpl.java
@Override
public void start() {
    // pass a copy of config to ContainerManagementProtocolProxy until YARN-3497 is fixed
    cmProxy = new ContainerManagementProtocolProxy(conf);
    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("ContainerLauncher #%d").setDaemon(true).build();
    // Start with a default core-pool size of 10 and change it dynamically.
    launcherPool = new ThreadPoolExecutor(INITIAL_POOL_SIZE, Integer.MAX_VALUE, 1, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>(), tf, new CustomizedRejectedExecutionHandler());
    eventHandlingThread = new Thread() {

        @Override
        public void run() {
            ContainerOp event = null;
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    event = eventQueue.take();
                } catch (InterruptedException e) {
                    if (!serviceStopped.get()) {
                        LOG.error("Returning, interrupted : " + e);
                    }
                    return;
                }
                int poolSize = launcherPool.getCorePoolSize();
                // maximum limit yet.
                if (poolSize != limitOnPoolSize) {
                    // nodes where containers will run at *this* point of time. This is
                    // *not* the cluster size and doesn't need to be.
                    int numNodes = getContext().getNumNodes(TezConstants.getTezYarnServicePluginName());
                    int idealPoolSize = Math.min(limitOnPoolSize, numNodes);
                    if (poolSize < idealPoolSize) {
                        // Bump up the pool size to idealPoolSize+INITIAL_POOL_SIZE, the
                        // later is just a buffer so we are not always increasing the
                        // pool-size
                        int newPoolSize = Math.min(limitOnPoolSize, idealPoolSize + INITIAL_POOL_SIZE);
                        LOG.info("Setting ContainerLauncher pool size to " + newPoolSize + " as number-of-nodes to talk to is " + numNodes);
                        launcherPool.setCorePoolSize(newPoolSize);
                    }
                }
                // the events from the queue are handled in parallel
                // using a thread pool
                launcherPool.execute(createEventProcessor(event));
            // TODO: Group launching of multiple containers to a single
            // NodeManager into a single connection
            }
        }
    };
    eventHandlingThread.setName("ContainerLauncher Event Handler");
    eventHandlingThread.start();
}

71. ExecutorUtils#createSingleThreadDeamonPool()

Project: stagemonitor
File: ExecutorUtils.java
public static ThreadPoolExecutor createSingleThreadDeamonPool(final String threadName, int queueCapacity) {
    final ThreadFactory daemonThreadFactory = new NamedThreadFactory(threadName);
    return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(queueCapacity), daemonThreadFactory) {

        @Override
        public String toString() {
            return super.toString() + "(thread name = " + threadName + ")";
        }

        /**
			 * Overriding this method makes sure that exceptions thrown by a task are not silently swallowed.
			 * <p/>
			 * Thanks to nos for this solution: http://stackoverflow.com/a/2248203/1125055
			 */
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            if (t == null && r instanceof Future<?>) {
                try {
                    Future<?> future = (Future<?>) r;
                    if (future.isDone()) {
                        future.get();
                    }
                } catch (CancellationException ce) {
                    t = ce;
                } catch (ExecutionException ee) {
                    t = ee.getCause();
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
            if (t != null) {
                logger.warn("Error while executing task in " + this, t);
            }
        }
    };
}

72. SleuthRxJavaSchedulersHookTests#executorService()

Project: spring-cloud-sleuth
File: SleuthRxJavaSchedulersHookTests.java
private ExecutorService executorService() {
    ThreadFactory threadFactory =  r -> {
        Thread thread = new Thread(r);
        thread.setName("MyCustomThread10");
        return thread;
    };
    return Executors.newSingleThreadExecutor(threadFactory);
}

73. UploadJarsMojo#execute()

Project: SlimFast
File: UploadJarsMojo.java
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().info("Skipping plugin execution");
        return;
    }
    LocalArtifactWrapper artifactWrapper = ArtifactHelper.getArtifactPaths(beanConfigurator, project);
    final UploadConfiguration configuration = buildConfiguration(artifactWrapper.getPrefix());
    FileHelper.ensureDirectoryExists(configuration.getOutputFile().getParent());
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("slimfast-upload").setDaemon(true).build();
    ExecutorService executor = Executors.newFixedThreadPool(s3UploadThreads, threadFactory);
    final FileUploader uploader = instantiateFileUploader();
    uploader.init(configuration, getLog());
    List<Future<?>> futures = new ArrayList<>();
    for (final LocalArtifact artifact : artifactWrapper.getArtifacts()) {
        futures.add(executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                uploader.upload(configuration, artifact);
                return null;
            }
        }));
    }
    executor.shutdown();
    waitForUploadsToFinish(executor, futures);
    uploader.destroy();
}

74. DownloadJarsMojo#execute()

Project: SlimFast
File: DownloadJarsMojo.java
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    S3ArtifactWrapper wrapper = readArtifactInfo();
    final DownloadConfiguration configuration = buildConfiguration(wrapper.getPrefix());
    FileHelper.ensureDirectoryExists(configuration.getCacheDirectory());
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("slimfast-download").setDaemon(true).build();
    ExecutorService executor = Executors.newFixedThreadPool(s3DownloadThreads, threadFactory);
    final FileDownloader downloader = instantiateFileDownloader();
    downloader.init(configuration, getLog());
    List<Future<?>> futures = new ArrayList<>();
    for (final S3Artifact artifact : wrapper.getArtifacts()) {
        futures.add(executor.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                downloader.download(configuration, artifact);
                return null;
            }
        }));
    }
    executor.shutdown();
    waitForDownloadsToFinish(executor, futures);
    downloader.destroy();
}

75. PollScheduler#start()

Project: servo
File: PollScheduler.java
/**
   * Start scheduling tasks with a default thread pool, sized based on the
   * number of available processors.
   */
public void start() {
    int numThreads = Runtime.getRuntime().availableProcessors();
    ThreadFactory factory = ThreadFactories.withName("ServoPollScheduler-%d");
    start(Executors.newScheduledThreadPool(numThreads, factory));
}

76. RxJavaSchedulersHookTest#newThreadSchedulerUsesSuppliedThreadFactory()

Project: RxJava
File: RxJavaSchedulersHookTest.java
@Test
public void newThreadSchedulerUsesSuppliedThreadFactory() throws InterruptedException {
    final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            threadRef.set(thread);
            return thread;
        }
    };
    Scheduler scheduler = RxJavaSchedulersHook.createNewThreadScheduler(threadFactory);
    Worker worker = scheduler.createWorker();
    final CountDownLatch latch = new CountDownLatch(1);
    worker.schedule(new Action0() {

        @Override
        public void call() {
            assertSame(threadRef.get(), Thread.currentThread());
            latch.countDown();
        }
    });
    assertTrue(latch.await(10, SECONDS));
    if (scheduler instanceof SchedulerLifecycle) {
        ((SchedulerLifecycle) scheduler).shutdown();
    }
}

77. RxJavaSchedulersHookTest#ioSchedulerUsesSuppliedThreadFactory()

Project: RxJava
File: RxJavaSchedulersHookTest.java
@Test
public void ioSchedulerUsesSuppliedThreadFactory() throws InterruptedException {
    final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            threadRef.set(thread);
            return thread;
        }
    };
    Scheduler scheduler = RxJavaSchedulersHook.createIoScheduler(threadFactory);
    Worker worker = scheduler.createWorker();
    final CountDownLatch latch = new CountDownLatch(1);
    worker.schedule(new Action0() {

        @Override
        public void call() {
            assertSame(threadRef.get(), Thread.currentThread());
            latch.countDown();
        }
    });
    assertTrue(latch.await(10, SECONDS));
    if (scheduler instanceof SchedulerLifecycle) {
        ((SchedulerLifecycle) scheduler).shutdown();
    }
}

78. RxJavaSchedulersHookTest#computationSchedulerUsesSuppliedThreadFactory()

Project: RxJava
File: RxJavaSchedulersHookTest.java
@Test
public void computationSchedulerUsesSuppliedThreadFactory() throws InterruptedException {
    final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            threadRef.set(thread);
            return thread;
        }
    };
    Scheduler scheduler = RxJavaSchedulersHook.createComputationScheduler(threadFactory);
    Worker worker = scheduler.createWorker();
    final CountDownLatch latch = new CountDownLatch(1);
    worker.schedule(new Action0() {

        @Override
        public void call() {
            assertSame(threadRef.get(), Thread.currentThread());
            latch.countDown();
        }
    });
    assertTrue(latch.await(10, SECONDS));
    if (scheduler instanceof SchedulerLifecycle) {
        ((SchedulerLifecycle) scheduler).shutdown();
    }
}

79. AsyncServer#newSynchronousWorkers()

Project: RemoteDroid
File: AsyncServer.java
private static ExecutorService newSynchronousWorkers() {
    ThreadFactory tf = new NamedThreadFactory("AsyncServer-worker-");
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 4, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), tf);
    return tpe;
}

80. AsyncQueueingExecutor#createExecuteThread()

Project: pinpoint
File: AsyncQueueingExecutor.java
private Thread createExecuteThread(String executorName) {
    final ThreadFactory threadFactory = new PinpointThreadFactory(executorName, true);
    Thread thread = threadFactory.newThread(this);
    thread.start();
    return thread;
}

81. ZookeeperJobWorker#start()

Project: pinpoint
File: ZookeeperJobWorker.java
public void start() {
    final ThreadFactory threadFactory = new PinpointThreadFactory(this.getClass().getSimpleName(), true);
    this.workerThread = threadFactory.newThread(this);
    switch(this.workerState.getCurrentState()) {
        case NEW:
            if (this.workerState.changeStateInitializing()) {
                logger.info("start() started.");
                workerState.changeStateStarted();
                this.workerThread.start();
                logger.info("start() completed.");
                break;
            }
        case INITIALIZING:
            logger.info("start() failed. cause: already initializing.");
            break;
        case STARTED:
            logger.info("start() failed. cause: already initializing.");
            break;
        case DESTROYING:
            throw new IllegalStateException("Already destroying.");
        case STOPPED:
            throw new IllegalStateException(ClassUtils.simpleClassName(this) + " start() failed. caused:Already stopped.");
        case ILLEGAL_STATE:
            throw new IllegalStateException(ClassUtils.simpleClassName(this) + " start() failed. caused:Invalid State.");
    }
}

82. ScheduledExecutorServiceSpike#main()

Project: owner
File: ScheduledExecutorServiceSpike.java
public static void main(String[] args) throws InterruptedException {
    ThreadFactory tf = new ThreadFactory() {

        public Thread newThread(Runnable r) {
            try {
                Thread result = new Thread(r);
                result.setDaemon(true);
                return result;
            } finally {
                System.out.println("new thread created");
            }
        }
    };
    ScheduledExecutorService stp = Executors.newSingleThreadScheduledExecutor(tf);
    stp.scheduleAtFixedRate(new Runnable() {

        int count = 0;

        public void run() {
            if (count++ % 2 == 0)
                System.out.printf("*");
        }
    }, 500, 500, TimeUnit.MILLISECONDS);
    stp.scheduleAtFixedRate(new Runnable() {

        int count = 0;

        public void run() {
            ++count;
            if (count != 5 && count != 10)
                System.out.printf(".");
            if (count == 10)
                count = 0;
        }
    }, 100, 100, TimeUnit.MILLISECONDS);
    stp.scheduleAtFixedRate(new Runnable() {

        int count = 0;

        public void run() {
            System.out.print(++count);
        }
    }, 1000, 1000, TimeUnit.MILLISECONDS);
    Thread.sleep(10000L);
}

83. ExecutorUtils#buildExecutor()

Project: oryx
File: ExecutorUtils.java
public static ExecutorService buildExecutor(String name, int parallelism) {
    ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name + "-%d").setDaemon(true).build();
    log.info("Executing {} with parallelism {}", name, parallelism);
    return Executors.newFixedThreadPool(parallelism, factory);
}

84. Threading#newScheduledPool()

Project: Orchid
File: Threading.java
public static ScheduledExecutorService newScheduledPool(final String name) {
    ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(name + "-%d").build();
    return Executors.newScheduledThreadPool(1, factory);
}

85. Threading#newSingleThreadScheduledPool()

Project: Orchid
File: Threading.java
public static ScheduledExecutorService newSingleThreadScheduledPool(final String name) {
    ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(name + "-%d").build();
    return Executors.newSingleThreadScheduledExecutor(factory);
}

86. Threading#newPool()

Project: Orchid
File: Threading.java
public static ExecutorService newPool(final String name) {
    ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(name + "-%d").build();
    return Executors.newCachedThreadPool(factory);
}

87. FlakyThreadFactory#test()

Project: openjdk
File: FlakyThreadFactory.java
void test(final Class<?> exceptionClass, final ThreadFactory failingThreadFactory) throws Throwable {
    ThreadFactory flakyThreadFactory = new ThreadFactory() {

        int seq = 0;

        public Thread newThread(Runnable r) {
            if (seq++ < 4)
                return new Thread(r);
            else
                return failingThreadFactory.newThread(r);
        }
    };
    ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue(), flakyThreadFactory);
    try {
        for (int i = 0; i < 8; i++) pool.submit(new Runnable() {

            public void run() {
            }
        });
        check(exceptionClass == null);
    } catch (Throwable t) {
        check(exceptionClass.isInstance(t));
    }
    pool.shutdown();
    check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}

88. ScheduledExecutorTest#testSetThreadFactory()

Project: openjdk
File: ScheduledExecutorTest.java
/**
     * setThreadFactory sets the thread factory returned by getThreadFactory
     */
public void testSetThreadFactory() throws InterruptedException {
    ThreadFactory threadFactory = new SimpleThreadFactory();
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        p.setThreadFactory(threadFactory);
        assertSame(threadFactory, p.getThreadFactory());
    }
}

89. ScheduledExecutorTest#testGetThreadFactory()

Project: openjdk
File: ScheduledExecutorTest.java
/**
     * getThreadFactory returns factory in constructor if not set
     */
public void testGetThreadFactory() throws InterruptedException {
    final ThreadFactory threadFactory = new SimpleThreadFactory();
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, threadFactory);
    try (PoolCleaner cleaner = cleaner(p)) {
        assertSame(threadFactory, p.getThreadFactory());
    }
}

90. ScheduledExecutorSubclassTest#testSetThreadFactory()

Project: openjdk
File: ScheduledExecutorSubclassTest.java
/**
     * setThreadFactory sets the thread factory returned by getThreadFactory
     */
public void testSetThreadFactory() {
    final ThreadFactory threadFactory = new SimpleThreadFactory();
    final CustomExecutor p = new CustomExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        p.setThreadFactory(threadFactory);
        assertSame(threadFactory, p.getThreadFactory());
    }
}

91. ScheduledExecutorSubclassTest#testGetThreadFactory()

Project: openjdk
File: ScheduledExecutorSubclassTest.java
/**
     * getThreadFactory returns factory in constructor if not set
     */
public void testGetThreadFactory() {
    final ThreadFactory threadFactory = new SimpleThreadFactory();
    final CustomExecutor p = new CustomExecutor(1, threadFactory);
    try (PoolCleaner cleaner = cleaner(p)) {
        assertSame(threadFactory, p.getThreadFactory());
    }
}

92. Leaky#main()

Project: openjdk
File: Leaky.java
public static void main(String[] args) throws Exception {
    ThreadFactory threadFactory = new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    };
    AsynchronousChannelGroup group = AsynchronousChannelGroup.withFixedThreadPool(4, threadFactory);
    final int CONNECTION_COUNT = 10;
    Connection[] connections = new Connection[CONNECTION_COUNT];
    for (int i = 0; i < CONNECTION_COUNT; i++) {
        connections[i] = new Connection(group);
    }
    for (int i = 0; i < 1024; i++) {
        // initiate reads
        for (Connection conn : connections) {
            conn.startRead();
        }
        // write data so that the read can complete
        for (Connection conn : connections) {
            conn.write();
        }
        // complete read
        for (Connection conn : connections) {
            conn.finishRead();
        }
    }
    // print summary of buffer pool usage
    List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) System.out.format("         %8s             ", pool.getName());
    System.out.println();
    for (int i = 0; i < pools.size(); i++) System.out.format("%6s %10s %10s  ", "Count", "Capacity", "Memory");
    System.out.println();
    for (BufferPoolMXBean pool : pools) {
        System.out.format("%6d %10d %10d  ", pool.getCount(), pool.getTotalCapacity(), pool.getMemoryUsed());
    }
    System.out.println();
}

93. ToolsTest#exceptionHandler()

Project: onos
File: ToolsTest.java
@Test
public void exceptionHandler() throws InterruptedException {
    ThreadFactory f = Tools.namedThreads("foo");
    Thread t = f.newThread(() -> {
        throw new IllegalStateException("BOOM!");
    });
    assertNotNull("thread should have exception handler", t.getUncaughtExceptionHandler());
    t.start();
    assertAfter(100, () -> assertEquals("incorrect thread state", Thread.State.TERMINATED, t.getState()));
}

94. ToolsTest#groupedThreads()

Project: onos
File: ToolsTest.java
@Test
public void groupedThreads() {
    ThreadFactory f = Tools.groupedThreads("foo/bar-me", "foo-%d");
    Thread t = f.newThread(() -> TestTools.print("yo"));
    assertTrue("wrong pattern", t.getName().startsWith("foo-bar-me-foo-"));
    assertTrue("wrong group", t.getThreadGroup().getName().equals("foo/bar-me"));
}

95. ToolsTest#namedThreads()

Project: onos
File: ToolsTest.java
@Test
public void namedThreads() {
    ThreadFactory f = Tools.namedThreads("foo-%d");
    Thread t = f.newThread(() -> TestTools.print("yo"));
    assertTrue("wrong pattern", t.getName().startsWith("foo-"));
}

96. ODEServer#initBpelServer()

Project: ode
File: ODEServer.java
private void initBpelServer(EndpointReferenceContextImpl eprContext) {
    if (__log.isDebugEnabled()) {
        __log.debug("ODE initializing");
    }
    ThreadFactory threadFactory = new ThreadFactory() {

        int threadNumber = 0;

        public Thread newThread(Runnable r) {
            threadNumber += 1;
            Thread t = new Thread(r, "ODEServer-" + threadNumber);
            t.setDaemon(true);
            return t;
        }
    };
    if (_odeConfig.getThreadPoolMaxSize() == 0)
        _executorService = Executors.newCachedThreadPool(threadFactory);
    else
        _executorService = Executors.newFixedThreadPool(_odeConfig.getThreadPoolMaxSize(), threadFactory);
    {
        List<String> targets = new ArrayList<String>();
        Collections.addAll(targets, _odeConfig.getProperty("cluster.localRoute.targets", "").split(","));
        _clusterUrlTransformer = new ClusterUrlTransformer(targets, _odeConfig.getProperty("cluster.localRoute.base", "http://localhost:8080/ode/processes/"));
    }
    _bpelServer = new BpelServerImpl();
    _scheduler = createScheduler();
    _scheduler.setJobProcessor(_bpelServer);
    BpelServerImpl.PolledRunnableProcessor polledRunnableProcessor = new BpelServerImpl.PolledRunnableProcessor();
    polledRunnableProcessor.setPolledRunnableExecutorService(_executorService);
    polledRunnableProcessor.setContexts(_bpelServer.getContexts());
    _scheduler.setPolledRunnableProcesser(polledRunnableProcessor);
    _cronScheduler = new CronScheduler();
    _cronScheduler.setScheduledTaskExec(_executorService);
    _cronScheduler.setContexts(_bpelServer.getContexts());
    _bpelServer.setCronScheduler(_cronScheduler);
    _bpelServer.setDaoConnectionFactory(_daoCF);
    _bpelServer.setClusterManagerImpl(_clusterManager);
    _bpelServer.setInMemDaoConnectionFactory(new BpelDAOConnectionFactoryImpl(_scheduler, _odeConfig.getInMemMexTtl()));
    _bpelServer.setEndpointReferenceContext(eprContext);
    _bpelServer.setMessageExchangeContext(new MessageExchangeContextImpl(this));
    _bpelServer.setBindingContext(new BindingContextImpl(this));
    _bpelServer.setScheduler(_scheduler);
    if (_odeConfig.isDehydrationEnabled()) {
        CountLRUDehydrationPolicy dehy = new CountLRUDehydrationPolicy();
        dehy.setProcessMaxAge(_odeConfig.getDehydrationMaximumAge());
        dehy.setProcessMaxCount(_odeConfig.getDehydrationMaximumCount());
        _bpelServer.setDehydrationPolicy(dehy);
    }
    _bpelServer.setMigrationTransactionTimeout(_odeConfig.getMigrationTransactionTimeout());
    _bpelServer.setConfigProperties(_odeConfig.getProperties());
    _bpelServer.init();
    _bpelServer.setInstanceThrottledMaximumCount(_odeConfig.getInstanceThrottledMaximumCount());
    _bpelServer.setProcessThrottledMaximumCount(_odeConfig.getProcessThrottledMaximumCount());
    _bpelServer.setProcessThrottledMaximumSize(_odeConfig.getProcessThrottledMaximumSize());
    _bpelServer.setHydrationLazy(_odeConfig.isHydrationLazy());
    _bpelServer.setHydrationLazyMinimumSize(_odeConfig.getHydrationLazyMinimumSize());
}

97. MsgEchoPeerBase#run()

Project: netty
File: MsgEchoPeerBase.java
public void run() throws Exception {
    // Configure the peer.
    final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER);
    try {
        final Bootstrap boot = new Bootstrap();
        boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS).handler(new ChannelInitializer<UdtChannel>() {

            @Override
            public void initChannel(final UdtChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoPeerHandler(messageSize));
            }
        });
        // Start the peer.
        final ChannelFuture f = boot.connect(peer, self).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        connectGroup.shutdownGracefully();
    }
}

98. MsgEchoClient#main()

Project: netty
File: MsgEchoClient.java
public static void main(String[] args) throws Exception {
    // Configure the client.
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER);
    try {
        final Bootstrap boot = new Bootstrap();
        boot.group(connectGroup).channelFactory(NioUdtProvider.MESSAGE_CONNECTOR).handler(new ChannelInitializer<UdtChannel>() {

            @Override
            public void initChannel(final UdtChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoClientHandler());
            }
        });
        // Start the client.
        final ChannelFuture f = boot.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        connectGroup.shutdownGracefully();
    }
}

99. ByteEchoClient#main()

Project: netty
File: ByteEchoClient.java
public static void main(String[] args) throws Exception {
    // Configure the client.
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER);
    try {
        final Bootstrap boot = new Bootstrap();
        boot.group(connectGroup).channelFactory(NioUdtProvider.BYTE_CONNECTOR).handler(new ChannelInitializer<UdtChannel>() {

            @Override
            public void initChannel(final UdtChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoClientHandler());
            }
        });
        // Start the client.
        final ChannelFuture f = boot.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        connectGroup.shutdownGracefully();
    }
}

100. ThreadPoolManager#getGeneralStats()

Project: L2_GameServer_T0
File: ThreadPoolManager.java
public String getGeneralStats() {
    TextBuilder tb = new TextBuilder();
    ThreadFactory tf = _generalThreadPool.getThreadFactory();
    if (tf instanceof PriorityThreadFactory) {
        tb.append("General Thread Pool:\r\n");
        tb.append("Tasks in the queue: " + _generalThreadPool.getQueue().size() + "\r\n");
        tb.append("Showing threads stack trace:\r\n");
        PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
        int count = ptf.getGroup().activeCount();
        Thread[] threads = new Thread[count + 2];
        ptf.getGroup().enumerate(threads);
        tb.append("There should be " + count + " Threads\r\n");
        for (Thread t : threads) {
            if (t == null) {
                continue;
            }
            tb.append(t.getName() + "\r\n");
            for (StackTraceElement ste : t.getStackTrace()) {
                tb.append(ste.toString());
                tb.append("\r\n");
            }
        }
    }
    tb.append("Packet Tp stack traces printed.\r\n");
    return tb.toString();
}