Example usage for java.util.concurrent Executors newCachedThreadPool

List of usage examples for java.util.concurrent Executors newCachedThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newCachedThreadPool.

Prototype

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available, and uses the provided ThreadFactory to create new threads when needed.

Usage

From source file:com.jgoetsch.eventtrader.source.SocketIOWebSocketMsgSource.java

@Override
protected void receiveMsgs() {
    final String baseThreadName = Thread.currentThread().getName();
    ThreadRenamingRunnable.setThreadNameDeterminer(ThreadNameDeterminer.CURRENT);
    ThreadFactory threadFactory = new ThreadFactory() {
        private AtomicInteger n = new AtomicInteger();

        public Thread newThread(Runnable r) {
            return new Thread(r, baseThreadName + "-w-" + n.incrementAndGet());
        }/*from  www . j a  va2 s  .co m*/
    };
    bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(threadFactory), Executors.newCachedThreadPool(threadFactory)));

    try {
        URI url = new URI(getTokenUrl());

        final WebSocketClientHandshaker handshaker = new WebSocketClientHandshakerFactory().newHandshaker(url,
                WebSocketVersion.V13, null, false, null);

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new HttpResponseDecoder());
                pipeline.addLast("encoder", new HttpRequestEncoder());
                pipeline.addLast("ws-handler", new WebSocketClientHandler(handshaker));
                pipeline.addLast("sio-handler", new SocketIOClientHandler());
                return pipeline;
            }
        });

        ChannelFuture future = bootstrap
                .connect(new InetSocketAddress(url.getHost(), url.getPort() == -1 ? 80 : url.getPort()));
        future.syncUninterruptibly();
        ch = future.getChannel();
        handshaker.handshake(ch).syncUninterruptibly();
        ch.getCloseFuture().awaitUninterruptibly();
    } catch (URISyntaxException use) {
        log.error("Invalid URL: {}", getUrl(), use);
    } catch (Exception e) {
        log.error("Error getting token", e);
    } finally {
        if (ch != null)
            ch.close();
        bootstrap.releaseExternalResources();
    }
}

From source file:sk.datalan.solr.impl.ConcurrentUpdateSolrServer.java

public ConcurrentUpdateSolrServer(String solrServerUrl, HttpClientBuilder clientBuilder, int queueSize,
        int threadCount) {
    this(solrServerUrl, clientBuilder, queueSize, threadCount,
            Executors.newCachedThreadPool(new SolrjNamedThreadFactory("concurrentUpdateScheduler")));
    shutdownExecutor = true;//w  w  w .  j  a v a  2  s.c om
}

From source file:org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer.java

public ConcurrentUpdateSolrServer(String solrServerUrl, HttpClient client, int queueSize, int threadCount) {
    this(solrServerUrl, client, queueSize, threadCount,
            Executors.newCachedThreadPool(new SolrjNamedThreadFactory("concurrentUpdateScheduler")));
    shutdownExecutor = true;//from w ww .j  av  a  2s.  c  o  m
}

From source file:com.ebay.jetstream.event.processor.esper.raw.EsperTest.java

@Test
public void aggregationTest() {
    Configuration configuration = new Configuration();
    configuration.configure(//from   w w w . ja  va2 s  .  c om
            new File("src/test/java/com/ebay/jetstream/event/processor/esper/raw/EsperTestConfig.xml"));
    EPServiceProvider epService = EPServiceProviderManager.getProvider("EsperTest", configuration);
    EsperTestAggregationStatement esperStmt = new EsperTestAggregationStatement(epService.getEPAdministrator());
    EsperTestAggregationListener listener = new EsperTestAggregationListener();
    esperStmt.addListener(listener);

    ExecutorService threadPool = Executors.newCachedThreadPool(new EsperTestThreadFactory());
    EsperTestAggregationRunnable runnables[] = new EsperTestAggregationRunnable[THREADS_NUM_AGGRTEST];
    try {
        for (int i = 0; i < THREADS_NUM_AGGRTEST; i++) {
            runnables[i] = new EsperTestAggregationRunnable(epService, i);
            threadPool.submit(runnables[i]);
        }
        threadPool.shutdown();
        threadPool.awaitTermination(200, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        fail("InterruptedException: " + e.getMessage());
    }
    assertTrue("ExecutorService failed to shut down properly", threadPool.isShutdown());
    assertEquals(THREADS_NUM_AGGRTEST * 2, listener.getCount());
    assertEquals(THREADS_NUM_AGGRTEST, m_aggregationResults.size()); // only one result per oroginal event
    for (int i = 0; i < THREADS_NUM_AGGRTEST; i++) {
        assertEquals(11.0 + 4. * i, m_aggregationResults.get(i), 1.e-06);
    }
    assertEquals(THREADS_NUM_AGGRTEST, m_aggregationAvgResults.size()); // only one result per oroginal event
    for (int i = 0; i < THREADS_NUM_AGGRTEST; i++) {
        assertEquals((11.0 + 4. * i) / 4., m_aggregationAvgResults.get(i), 1.e-06);
    }
}

From source file:com.yahoo.omid.tsoclient.TSOClientImpl.java

TSOClientImpl(Configuration conf, MetricRegistry metrics) {

    this.metrics = metrics;

    // Start client with Nb of active threads = 3 as maximum.
    int tsoExecutorThreads = conf.getInt(TSO_EXECUTOR_THREAD_NUM_CONFKEY, DEFAULT_TSO_EXECUTOR_THREAD_NUM);

    factory = new NioClientSocketChannelFactory(
            Executors
                    .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()),
            tsoExecutorThreads);/*from ww  w .  j  av a 2s  .  co m*/
    // Create the bootstrap
    bootstrap = new ClientBootstrap(factory);

    requestTimeoutMs = conf.getInt(REQUEST_TIMEOUT_IN_MS_CONFKEY, DEFAULT_REQUEST_TIMEOUT_MS);
    requestMaxRetries = conf.getInt(REQUEST_MAX_RETRIES_CONFKEY, DEFAULT_TSO_MAX_REQUEST_RETRIES);
    retryDelayMs = conf.getInt(TSO_RETRY_DELAY_MS_CONFKEY, DEFAULT_TSO_RETRY_DELAY_MS);

    LOG.info("Connecting to TSO...");
    // Try to connect to TSO from ZK. If fails, go through host:port config
    try {
        connectToZK(conf);
        configureCurrentTSOServerZNodeCache();
        HostAndPort hp = getCurrentTSOHostAndPortFoundInZK();
        LOG.info("\t* Current TSO host:port found in ZK: {}", hp);
        setTSOAddress(hp.getHostText(), hp.getPort());
    } catch (ZKException e) {
        LOG.warn("A problem connecting to TSO was found ({}). Trying to connect directly with host:port",
                e.getMessage());
        String host = conf.getString(TSO_HOST_CONFKEY);
        int port = conf.getInt(TSO_PORT_CONFKEY, DEFAULT_TSO_PORT);
        if (host == null) {
            throw new IllegalArgumentException("tso.host missing from configuration");
        }
        setTSOAddress(host, port);
    }

    fsmExecutor = Executors
            .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
    fsm = new FsmImpl(fsmExecutor);
    fsm.setInitState(new DisconnectedState(fsm));

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());
    pipeline.addLast("handler", new Handler(fsm));

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);
}

From source file:net.NettyEngine3.core.NServerFrameNettyStart.java

/**
 * main_reactor and  sub_reactor/*from ww w.  j a  v a  2 s . c  o  m*/
 * @return
 */
@Override
public Bootstrap getServerBootstrap() {
    ChannelFactory factory = new NioServerSocketChannelFactory(
            Executors.newFixedThreadPool(0x1,
                    new PriorityThreadFactory("@+main_reactor+@", Thread.NORM_PRIORITY)),
            Executors.newCachedThreadPool(
                    new PriorityThreadFactory("@+sub_reactor+@", Thread.NORM_PRIORITY)));
    bootstrap = new ServerBootstrap(factory);
    return bootstrap;
}

From source file:hudson.cli.CLI.java

/**
 * @deprecated Specific to {@link Mode#REMOTING}.
 */// ww  w  .jav  a2 s . c o  m
@Deprecated
/*package*/ CLI(CLIConnectionFactory factory) throws IOException, InterruptedException {
    URL jenkins = factory.jenkins;
    this.httpsProxyTunnel = factory.httpsProxyTunnel;
    this.authorization = factory.authorization;
    ExecutorService exec = factory.exec;

    ownsPool = exec == null;
    pool = exec != null ? exec
            : Executors
                    .newCachedThreadPool(new NamingThreadFactory(Executors.defaultThreadFactory(), "CLI.pool"));

    Channel _channel;
    try {
        _channel = connectViaCliPort(jenkins, getCliTcpPort(jenkins));
    } catch (IOException e) {
        LOGGER.log(Level.FINE, "Failed to connect via CLI port. Falling back to HTTP", e);
        try {
            _channel = connectViaHttp(jenkins);
        } catch (IOException e2) {
            e.addSuppressed(e2);
            throw e;
        }
    }
    this.channel = _channel;

    // execute the command
    entryPoint = (CliEntryPoint) _channel.waitForRemoteProperty(CliEntryPoint.class.getName());

    if (entryPoint.protocolVersion() != CliEntryPoint.VERSION)
        throw new IOException(Messages.CLI_VersionMismatch());
}

From source file:com.flipkart.phantom.runtime.impl.server.netty.UDSNettyServer.java

/**
 * Interface method implementation. Creates server and worker thread pools if required and then calls {@link #afterPropertiesSet()} on the super class
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 *///from  w w w . j  a  v  a2 s  .  c o m
public void afterPropertiesSet() throws Exception {
    File[] junixDirectories = FileLocator.findDirectories(this.junixNativeLibDirectoryName, null);
    if (junixDirectories == null || junixDirectories.length == 0) {
        throw new RuntimeException("Did not find junixDirectory: " + junixNativeLibDirectoryName);
    }
    LOGGER.info("Found junixDirectory: " + junixDirectories[0].getAbsolutePath());
    System.setProperty(JUNIX_LIB_SYSTEM_PROPERTY, junixDirectories[0].getAbsolutePath());
    //Required properties
    Assert.notNull(this.socketDir, "socketDir is a required property for UDSNetworkServer");
    Assert.notNull(this.socketName, "socketName is a required property for UDSNetworkServer");
    //Create the socket file
    this.socketFile = new File(new File(this.socketDir), this.socketName);

    //Create socket address
    LOGGER.info("Socket file: " + this.socketFile.getAbsolutePath());
    try {
        this.socketAddress = new AFUNIXSocketAddress(this.socketFile);
    } catch (IOException e) {
        throw new RuntimeException("Error creating Socket Address. ", e);
    }
    if (this.getServerExecutors() == null) { // no executors have been set for server listener
        if (this.getServerPoolSize() != UDSNettyServer.INVALID_POOL_SIZE) { // thread pool size has been set. create and use a fixed thread pool
            this.setServerExecutors(Executors.newFixedThreadPool(this.getServerPoolSize(),
                    new NamedThreadFactory("UDSServer-Listener")));
        } else { // default behavior of creating and using a cached thread pool
            this.setServerExecutors(
                    Executors.newCachedThreadPool(new NamedThreadFactory("UDSServer-Listener")));
        }
    }
    if (this.getWorkerExecutors() == null) { // no executors have been set for workers
        if (this.getWorkerPoolSize() != UDSNettyServer.INVALID_POOL_SIZE) { // thread pool size has been set. create and use a fixed thread pool
            this.setWorkerExecutors(Executors.newFixedThreadPool(this.getWorkerPoolSize(),
                    new NamedThreadFactory("UDSServer-Worker")));
        } else { // default behavior of creating and using a cached thread pool
            this.setWorkerExecutors(Executors.newCachedThreadPool(new NamedThreadFactory("UDSServer-Worker")));
        }
    }
    super.afterPropertiesSet();
    LOGGER.info("UDS Server startup complete");
}

From source file:com.linkedin.pinot.core.data.manager.offline.OfflineTableDataManager.java

@Override
public void init(TableDataManagerConfig tableDataManagerConfig) {
    _tableDataManagerConfig = tableDataManagerConfig;
    _tableName = _tableDataManagerConfig.getTableName();

    LOGGER = LoggerFactory.getLogger(_tableName + "-OfflineTableDataManager");
    _currentNumberOfSegments = Metrics.newCounter(OfflineTableDataManager.class,
            _tableName + "-" + CommonConstants.Metric.Server.CURRENT_NUMBER_OF_SEGMENTS);
    _currentNumberOfDocuments = Metrics.newCounter(OfflineTableDataManager.class,
            _tableName + "-" + CommonConstants.Metric.Server.CURRENT_NUMBER_OF_DOCUMENTS);
    _numDeletedSegments = Metrics.newCounter(OfflineTableDataManager.class,
            _tableName + "-" + CommonConstants.Metric.Server.NUMBER_OF_DELETED_SEGMENTS);

    _tableDataDir = _tableDataManagerConfig.getDataDir();
    if (!new File(_tableDataDir).exists()) {
        new File(_tableDataDir).mkdirs();
    }/*from   w  ww  .  j a  v a2 s . c o  m*/
    _numberOfTableQueryExecutorThreads = _tableDataManagerConfig.getNumberOfTableQueryExecutorThreads();
    //_numberOfTableQueryExecutorThreads = 1;
    if (_numberOfTableQueryExecutorThreads > 0) {
        _queryExecutorService = Executors.newFixedThreadPool(_numberOfTableQueryExecutorThreads,
                new NamedThreadFactory("parallel-query-executor-" + _tableName));
    } else {
        _queryExecutorService = Executors
                .newCachedThreadPool(new NamedThreadFactory("parallel-query-executor-" + _tableName));
    }
    _readMode = ReadMode.valueOf(_tableDataManagerConfig.getReadMode());
    _indexLoadingConfigMetadata = _tableDataManagerConfig.getIndexLoadingConfigMetadata();
    LOGGER.info("Initialized table : " + _tableName + " with :\n\tData Directory: " + _tableDataDir
            + "\n\tRead Mode : " + _readMode + "\n\tQuery Exeutor with "
            + ((_numberOfTableQueryExecutorThreads > 0) ? _numberOfTableQueryExecutorThreads : "cached")
            + " threads");
}