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

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

Introduction

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

Prototype

public ThreadFactoryBuilder() 

Source Link

Document

Creates a new ThreadFactory builder.

Usage

From source file:org.apache.storm.metric.FileBasedEventLogger.java

private void setUpFlushTask() {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("event-logger-flush-%d")
            .setDaemon(true).build();//from w w w  .j  av a 2  s.  c  o  m

    flushScheduler = Executors.newSingleThreadScheduledExecutor(threadFactory);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (dirty) {
                    eventLogWriter.flush();
                    dirty = false;
                }
            } catch (IOException ex) {
                LOG.error("Error flushing " + eventLogPath, ex);
                throw new RuntimeException(ex);
            }
        }
    };

    flushScheduler.scheduleAtFixedRate(runnable, FLUSH_INTERVAL_MILLIS, FLUSH_INTERVAL_MILLIS,
            TimeUnit.MILLISECONDS);
}

From source file:org.glowroot.local.ui.HttpServer.java

HttpServer(String bindAddress, int port, int numWorkerThreads, LayoutService layoutService,
        Map<Pattern, HttpService> httpServices, HttpSessionManager httpSessionManager,
        List<Object> jsonServices) throws Exception {

    InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());

    ThreadFactory bossThreadFactory = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Glowroot-Http-Boss-%d").build();
    ThreadFactory workerThreadFactory = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Glowroot-Http-Worker-%d").build();
    bossGroup = new NioEventLoopGroup(1, bossThreadFactory);
    workerGroup = new NioEventLoopGroup(numWorkerThreads, workerThreadFactory);

    final HttpServerHandler handler = new HttpServerHandler(layoutService, httpServices, httpSessionManager,
            jsonServices);//from  www  .  java2 s.c  om

    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpServerCodec());
                    p.addLast(new HttpObjectAggregator(1048576));
                    p.addLast(new ConditionalHttpContentCompressor());
                    p.addLast(new ChunkedWriteHandler());
                    p.addLast(handler);
                }
            });
    this.handler = handler;
    logger.debug("<init>(): binding http server to port {}", port);
    this.bindAddress = bindAddress;
    Channel serverChannel;
    try {
        serverChannel = bootstrap.bind(new InetSocketAddress(bindAddress, port)).sync().channel();
    } catch (Exception e) {
        // FailedChannelFuture.sync() is using UNSAFE to re-throw checked exceptions
        try {
            serverChannel = bootstrap.bind(new InetSocketAddress(bindAddress, 0)).sync().channel();
        } catch (Exception f) {
            // FailedChannelFuture.sync() is using UNSAFE to re-throw checked exceptions\

            // clean up
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw f;
        }
        logger.error("error binding to port: {} (bound to port {} instead)", port,
                ((InetSocketAddress) serverChannel.localAddress()).getPort());
        // log exception at debug level
        logger.debug(e.getMessage(), e);
    }
    this.serverChannel = serverChannel;
    this.port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    logger.debug("<init>(): http server bound");
}

From source file:co.paralleluniverse.galaxy.core.NodeOrderedThreadPoolExecutor.java

@ConstructorProperties({ "cluster", "corePoolSize", "maximumPoolSize", "keepAliveTime", "unit", "maxQueueSize",
        "handler" })
public NodeOrderedThreadPoolExecutor(Cluster cluster, int corePoolSize, int maximumPoolSize, long keepAliveTime,
        TimeUnit unit, int maxQueueSize, RejectedExecutionHandler handler) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, maxQueueSize,
            new ThreadFactoryBuilder().setDaemon(true).build(), handler);
    cluster.addNodeChangeListener(listener);
}

From source file:com.vmware.photon.controller.common.zookeeper.ServiceConfig.java

@Inject
public ServiceConfig(CuratorFramework zkClient,
        @ServicePathCacheFactory PathChildrenCacheFactory childrenCacheFactory, @Assisted String serviceName)
        throws Exception {
    this.serviceName = serviceName;
    serviceConfigZKPath = "config/" + serviceName;
    ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("ZkServiceConfigPathChildrenCache" + "-%d").setDaemon(true).build();
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
    configCache = childrenCacheFactory.createPathCache(ZKPaths.makePath(serviceConfigZKPath, ""), executor);
    configCache.getListenable().addListener(this);
    configCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
    this.serviceConfig = new DataDictionary(zkClient, executor, serviceConfigZKPath);
    serviceStatusZKPath = ZKPaths.makePath(this.serviceConfigZKPath, STATUS_ZK_PATH);
}

From source file:com.rhythm.louie.server.TaskScheduler.java

private synchronized ScheduledExecutorService getScheduler() {
    if (scheduler == null) {
        if (jndi != null) {
            InitialContext ctx;/* w ww  .ja  va  2s .  co m*/
            try {
                ctx = new InitialContext();
                scheduler = (ManagedScheduledExecutorService) ctx.lookup(jndi);
                LoggerFactory.getLogger(TaskScheduler.class).info("Loaded TaskScheduler from JNDI resource.");
                return scheduler;
            } catch (NamingException ex) {
                LoggerFactory.getLogger(TaskScheduler.class)
                        .error("Failed to fetch TaskScheduler JNDI resource.");
            }
        }
        //load w/ no jndi config, or on failure of jndi lookup
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("louie-taskscheduler-%d")
                .build();
        scheduler = Executors.newScheduledThreadPool(poolSize, threadFactory);
    }
    return scheduler;
}

From source file:org.cinchapi.concourse.server.concurrent.ConcourseExecutors.java

/**
 * Return a thread factory that will name all threads using
 * {@code threadNamePrefix}.//from  w  w  w. j  a  v  a 2  s .com
 * 
 * @param threadNamePrefix
 * @return the thread factory
 */
private static ThreadFactory getThreadFactory(String threadNamePrefix) {
    return new ThreadFactoryBuilder().setNameFormat(threadNamePrefix + "-%d")
            .setUncaughtExceptionHandler(uncaughtExceptionHandler).build();
}

From source file:co.cask.cdap.master.startup.YarnCheck.java

@Override
public void run() {
    int yarnConnectTimeout = cConf.getInt(Constants.Startup.YARN_CONNECT_TIMEOUT_SECONDS, 60);
    LOG.info("Checking YARN availability -- may take up to {} seconds.", yarnConnectTimeout);

    final YarnClient yarnClient = YarnClient.createYarnClient();
    yarnClient.init(hConf);/*from w ww  .ja  va  2  s .c  o m*/

    List<NodeReport> nodeReports;
    // if yarn is not up, yarnClient.start() will hang.
    ExecutorService executorService = Executors
            .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("startup-checker").build());
    try {
        Future<List<NodeReport>> result = executorService.submit(new Callable<List<NodeReport>>() {
            @Override
            public List<NodeReport> call() throws Exception {
                yarnClient.start();
                return yarnClient.getNodeReports();
            }
        });
        nodeReports = result.get(yarnConnectTimeout, TimeUnit.SECONDS);
        LOG.info("  YARN availability successfully verified.");
    } catch (Exception e) {
        throw new RuntimeException("Unable to get status of YARN nodemanagers. "
                + "Please check that YARN is running "
                + "and that the correct Hadoop configuration (core-site.xml, yarn-site.xml) and libraries "
                + "are included in the CDAP master classpath.", e);
    } finally {
        try {
            yarnClient.stop();
        } catch (Exception e) {
            LOG.warn("Error stopping yarn client.", e);
        } finally {
            executorService.shutdown();
        }
    }

    checkResources(nodeReports);
}

From source file:org.wso2.andes.kernel.slot.SlotDeliveryWorkerManager.java

private SlotDeliveryWorkerManager() {
    int numberOfThreads = AndesConfigurationManager
            .readValue(AndesConfiguration.PERFORMANCE_TUNING_SLOTS_WORKER_THREAD_COUNT);
    long idleTaskDelay = AndesConfigurationManager
            .readValue(AndesConfiguration.PERFORMANCE_TUNING_SLOTS_IDLE_TASK_DELAY);

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("MessageDeliveryTaskThreadPool-%d")
            .build();//www.ja v a  2s  .c om

    taskManager = new TaskExecutorService<>(numberOfThreads, idleTaskDelay, threadFactory);
    taskManager.setExceptionHandler(new DeliveryTaskExceptionHandler());
}

From source file:com.ovea.cometd.WebSocketTransport.java

@Override
protected Executor newExecutor() {
    int size = getOption(THREAD_POOL_MAX_SIZE, 64);
    return Executors.newFixedThreadPool(size,
            new ThreadFactoryBuilder().setNameFormat("WebSocketTransport-Thread-%1s").build());
}

From source file:org.apache.phoenix.log.QueryLoggerDisruptor.java

public QueryLoggerDisruptor(Configuration configuration) throws SQLException {
    WaitStrategy waitStrategy;/*from w  ww.  java2  s .c  o m*/
    try {
        waitStrategy = (WaitStrategy) Class
                .forName(configuration.get(QueryServices.LOG_BUFFER_WAIT_STRATEGY, DEFAULT_WAIT_STRATEGY))
                .newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new SQLException(e);
    }

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("QueryLogger" + "-thread-%s")
            .setDaemon(true).setThreadFactory(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    final Thread result = Executors.defaultThreadFactory().newThread(r);
                    result.setContextClassLoader(QueryLoggerDisruptor.class.getClass().getClassLoader());
                    return result;
                }
            }).build();
    disruptor = new Disruptor<RingBufferEvent>(RingBufferEvent.FACTORY,
            configuration.getInt(QueryServices.LOG_BUFFER_SIZE, RING_BUFFER_SIZE), threadFactory,
            ProducerType.MULTI, waitStrategy);
    final ExceptionHandler<RingBufferEvent> errorHandler = new QueryLoggerDefaultExceptionHandler();
    disruptor.setDefaultExceptionHandler(errorHandler);

    final QueryLogDetailsEventHandler[] handlers = { new QueryLogDetailsEventHandler(configuration) };
    disruptor.handleEventsWith(handlers);
    LOG.info("Starting  QueryLoggerDisruptor for with ringbufferSize="
            + disruptor.getRingBuffer().getBufferSize() + ", waitStrategy="
            + waitStrategy.getClass().getSimpleName() + ", " + "exceptionHandler=" + errorHandler + "...");
    disruptor.start();

}