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() 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

Usage

From source file:ru.jts_dev.gameserver.config.GameIntegrationConfig.java

@Bean
public MessageChannel incomingPacketExecutorChannel() {
    // TODO: 07.12.15 investigate, may be should replace with spring TaskExecutor
    return new ExecutorChannel(Executors.newCachedThreadPool());
}

From source file:edu.lternet.pasta.portal.HarvestReportServlet.java

private void executeHarvesterReportManager() {
    HarvestReportManager harvestReportManager = new HarvestReportManager(harvesterPath, harvesterReportTTL);
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(harvestReportManager);
    executorService.shutdown();// w w  w .  j a  v  a 2s  .  c o  m
}

From source file:org.usergrid.mongo.MongoServer.java

public void startServer() {
    logger.info("Starting Usergrid Mongo Emulation Server");

    if (realm != null) {
        securityManager = new DefaultSecurityManager(realm);
    }//w  w w. ja  v a2  s  .c  o m

    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    bootstrap.setOption("child.bufferFactory", HeapChannelBufferFactory.getInstance(ByteOrder.LITTLE_ENDIAN));

    // Set up the pipeline factory.
    ExecutionHandler executionHandler = new ExecutionHandler(
            new OrderedMemoryAwareThreadPoolExecutor(16, 1048576, 1048576));

    bootstrap.setPipelineFactory(
            new MongoServerPipelineFactory(emf, smf, management, securityManager, executionHandler));

    // Bind and start to accept incoming connections.
    channel = bootstrap.bind(new InetSocketAddress(27017));

    logger.info("Usergrid Mongo API Emulation Server accepting connections...");
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

@Before
@SuppressWarnings("unchecked")
public void setup() {
    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override/*from  w w w  . j  ava2  s .  co  m*/
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();

    CoreEnvironment environment = mock(CoreEnvironment.class);
    when(environment.scheduler()).thenReturn(Schedulers.computation());
    when(environment.maxRequestLifetime()).thenReturn(10000L); // 10 seconds
    when(environment.autoreleaseAfter()).thenReturn(2000L);
    endpoint = mock(AbstractEndpoint.class);
    when(endpoint.environment()).thenReturn(environment);
    when(environment.userAgent()).thenReturn("Couchbase Client Mock");

    queue = new ArrayDeque<ViewRequest>();
    handler = new ViewHandler(endpoint, responseRingBuffer, queue, false);
    channel = new EmbeddedChannel(handler);
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void testMultipleClients() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);/* w  ww .ja  va 2 s  .  com*/

    waitForState(server, ServerState.RUNNING);

    final int numClients = 5;
    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < numClients; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient("testMultipleClients", port);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(10, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:org.cytoscape.app.internal.net.server.CyHttpdFactoryImpl.java

public void start() {
    synchronized (lock) {
        if (running)
            throw new IllegalStateException("server is running");
        executor = Executors.newCachedThreadPool();
        aborted = false;/*from   w ww.  ja v a  2  s.  c  o  m*/
        executor.execute(new ServerThread());
        while (!running) {
            try {
                lock.wait(500);
                if (aborted) {
                    return;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToTransformedPipelineOutputs() throws InterruptedException {

    // this test verifies that pipelines actions are only executed once, even if there are multiple concurrent subscribers
    firstStep = newPipelineWithResponseBody("{id:123}");
    secondStep = firstStep.applyAction(action);
    when(action.execute(any(), any())).thenReturn(firstStep.getOutput());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    CountDownLatch countDown = new CountDownLatch(100);
    ExecutorService executorService = Executors.newCachedThreadPool();
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();/*from w  w  w  .jav a 2  s . c om*/
            secondStep.getOutput().subscribe(Subscribers.empty());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    verify(action, times(1)).execute(any(), any());
}

From source file:com.nhn.android.archetype.base.AABaseApplicationOrg.java

protected void init() {
    workExecutor = Executors.newCachedThreadPool();
    statsWorkExecutor = Executors.newFixedThreadPool(1);

    handler = new Handler(Looper.getMainLooper());

    backgroundHandlerThread = new HandlerThread("BandBackgroundHandlerThread");
    backgroundHandlerThread.start();//w  w w .j  a  v  a 2 s  .  com

    backgroundHandler = new Handler(backgroundHandlerThread.getLooper());

    JsonWorker.init();

    logger.d("Application init completed.....");
}

From source file:voldemort.store.readonly.swapper.StoreSwapperTest.java

@Test
public void testAdminStoreSwapper() throws Exception {
    ExecutorService executor = Executors.newCachedThreadPool();

    try {/*www  . j  a v  a 2 s .com*/
        // Use the admin store swapper
        StoreSwapper swapper = new AdminStoreSwapper(cluster, executor, adminClient, 1000000, true, true);
        testFetchSwap(swapper);
    } finally {
        executor.shutdown();
    }
}

From source file:com.alliander.osgp.acceptancetests.config.OslpConfig.java

@Bean(destroyMethod = "releaseExternalResources")
public ClientBootstrap clientBootstrap() {
    final ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());

    final ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
        @Override// w ww  .  j  a v  a 2  s . co  m
        public ChannelPipeline getPipeline()
                throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException {
            final ChannelPipeline pipeline = Channels.pipeline();

            pipeline.addLast("oslpEncoder", new OslpEncoder());
            pipeline.addLast("oslpDecoder",
                    new OslpDecoder(OslpConfig.this.oslpSignature(), OslpConfig.this.oslpSignatureProvider()));
            pipeline.addLast("oslpSecurity", OslpConfig.this.oslpSecurityHandler());

            pipeline.addLast("oslpChannelHandler", OslpConfig.this.oslpChannelHandlerClient());

            return pipeline;
        }
    };

    final ClientBootstrap bootstrap = new ClientBootstrap(factory);

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", false);
    bootstrap.setOption("connectTimeoutMillis", this.connectionTimeout());

    bootstrap.setPipelineFactory(pipelineFactory);

    return bootstrap;
}