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:org.icgc.dcc.release.client.config.WorkflowConfig.java

@Bean
public ExecutorService executorService(@Value("${workflow.parallel}") boolean parallel) {
    if (parallel) {
        // Many threads: spawned
        return Executors.newCachedThreadPool();
    } else {//from   w ww .  j  a v a 2  s. c  om
        // Only one thread: main
        return MoreExecutors.sameThreadExecutor();
    }
}

From source file:ste.travian.gui.WorldController.java

protected WorldController() {
    world = null;
    mainWindow = null;
    allianceGroupsPanel = null;

    executor = Executors.newCachedThreadPool();
}

From source file:my.adam.smo.server.SocketServer.java

@Inject
public SocketServer(@Value("${server_worker_threads:10}") int workerCount) {
    bootstrap.setFactory(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerCount));

    ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
        @Override/*  w  ww . j a  v a  2s .  c o  m*/
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline p = Channels.pipeline();
            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("frameEncoder", new LengthFieldPrepender(4));//DownstreamHandler
            p.addLast("protobufEncoder", new ProtobufEncoder());//DownstreamHandler

            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, 4, 0, 4));//UpstreamHandler
            p.addLast("protobufDecoder", new ProtobufDecoder(RPCommunication.Request.getDefaultInstance()));//UpstreamHandler
            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    RPCommunication.Request request = (RPCommunication.Request) e.getMessage();
                    logger.trace("received request:" + request.toString());

                    if (enableAsymmetricEncryption) {
                        request = getAsymDecryptedRequest(request);
                        logger.trace("asymmetric encryption enabled, decrypted request: " + request.toString());
                    }

                    if (enableSymmetricEncryption) {
                        request = getDecryptedRequest(request);
                        logger.trace("symmetric encryption enabled, decrypted request: " + request.toString());
                    }

                    final RPCommunication.Request protoRequest = request;

                    RpcController dummyController = new DummyRpcController();
                    Service service = serviceMap.get(request.getServiceName());

                    logger.trace("got service: " + service + " for name " + request.getServiceName());

                    Descriptors.MethodDescriptor methodToCall = service.getDescriptorForType()
                            .findMethodByName(request.getMethodName());

                    logger.trace("got method: " + methodToCall + " for name " + request.getMethodName());

                    Message methodArguments = service.getRequestPrototype(methodToCall).newBuilderForType()
                            .mergeFrom(request.getMethodArgument()).build();

                    logger.trace("get method arguments from request " + methodArguments.toString());

                    RpcCallback<Message> callback = new RpcCallback<Message>() {
                        @Override
                        public void run(Message parameter) {
                            RPCommunication.Response response = RPCommunication.Response.newBuilder()
                                    .setResponse(parameter.toByteString())
                                    .setRequestId(protoRequest.getRequestId()).build();

                            //encryption
                            if (enableSymmetricEncryption) {
                                response = getEncryptedResponse(response);
                                logger.trace("symmetric encryption enabled, encrypted response: "
                                        + response.toString());
                            }

                            if (enableAsymmetricEncryption) {
                                response = getAsymEncryptedResponse(response);
                                logger.trace("asymmetric encryption enabled, encrypted response: "
                                        + response.toString());
                            }

                            e.getChannel().write(response);
                            logger.trace("finishing call, response sent");
                        }
                    };
                    logger.trace("calling " + methodToCall.getFullName());
                    service.callMethod(methodToCall, dummyController, methodArguments, callback);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });
            return p;
        }
    };
    bootstrap.setPipelineFactory(pipelineFactory);
}

From source file:com.gitblit.plugin.slack.Slacker.java

Slacker(IRuntimeManager runtimeManager) {
    this.runtimeManager = runtimeManager;
    this.taskPool = Executors.newCachedThreadPool();
}

From source file:jenkins.plugins.elanceodesk.workplace.notifier.HttpWorkerTest.java

@Test
public void testSendingMultipleWebhooks() throws IOException, InterruptedException {
    ExecutorService executorService = Executors.newCachedThreadPool();
    HttpWorker worker1 = new HttpWorker("http://localhost:8000/test1", "test1body", 30000, 1,
            Mockito.mock(PrintStream.class));
    HttpWorker worker2 = new HttpWorker("http://localhost:8000/test2", "test2body", 30000, 1,
            Mockito.mock(PrintStream.class));
    executorService.submit(worker1);/*from  w ww . j av a 2s . c  om*/
    executorService.submit(worker2);
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.SECONDS);
    Assert.assertTrue(MyHandler.getTest1Result());
    Assert.assertTrue(MyHandler.getTest2Result());
}

From source file:my.adam.smo.client.HTTPClient.java

@Inject
public HTTPClient(@Value("${client_worker_threads:10}") int workerThreads) {
    bootstrap.setFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerThreads));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override//from  w ww  .  jav  a2s .c  om
        public ChannelPipeline getPipeline() throws Exception {
            StopWatch stopWatch = new StopWatch("getPipeline");
            stopWatch.start();

            ChannelPipeline p = Channels.pipeline();

            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("codec", new HttpClientCodec());
            p.addLast("chunkAggregator", new HttpChunkAggregator(MAX_CONTENT_LENGTH));
            p.addLast("chunkedWriter", new ChunkedWriteHandler());
            p.addLast("decompressor", new HttpContentDecompressor());

            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    HttpResponse httpResponse = (HttpResponse) e.getMessage();

                    ChannelBuffer cb = Base64.decode(httpResponse.getContent(), Base64Dialect.STANDARD);

                    RPCommunication.Response response = RPCommunication.Response
                            .parseFrom(CodedInputStream.newInstance(cb.copy(0, cb.readableBytes()).array()));
                    logger.trace("received response:" + response);

                    //encryption
                    if (enableAsymmetricEncryption) {
                        response = getAsymDecryptedResponse(response);
                        logger.trace(
                                "asymmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    if (enableSymmetricEncryption) {
                        response = getDecryptedResponse(response);
                        logger.trace("symmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    Message msg = descriptorProtoMap.remove(response.getRequestId());
                    Message m = msg.getParserForType().parseFrom(response.getResponse());
                    callbackMap.remove(response.getRequestId()).run(m);

                    super.messageReceived(ctx, e);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });

            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
            return p;
        }
    });
}

From source file:my.adam.smo.client.SocketClient.java

@Inject
public SocketClient(@Value("${client_worker_threads:10}") int workerThreads) {
    bootstrap.setFactory(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool(), workerThreads));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override//  ww  w.ja  va  2s  .  c o m
        public ChannelPipeline getPipeline() throws Exception {
            StopWatch stopWatch = new StopWatch("getPipeline");
            stopWatch.start();

            ChannelPipeline p = Channels.pipeline();

            if (enableTrafficLogging) {
                InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
                p.addLast("logger", new LoggingHandler(InternalLogLevel.DEBUG));
            }

            p.addLast("frameEncoder", new LengthFieldPrepender(4));//DownstreamHandler
            p.addLast("protobufEncoder", new ProtobufEncoder());//DownstreamHandler

            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, 4, 0, 4));//UpstreamHandler
            p.addLast("protobufDecoder", new ProtobufDecoder(RPCommunication.Response.getDefaultInstance()));//UpstreamHandler
            p.addLast("handler", new SimpleChannelUpstreamHandler() {
                @Override
                public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                    StopWatch stopWatch = new StopWatch("messageReceived");
                    stopWatch.start();

                    RPCommunication.Response response = (RPCommunication.Response) e.getMessage();
                    logger.trace("received response:" + response);

                    //encryption
                    if (enableAsymmetricEncryption) {
                        response = getAsymDecryptedResponse(response);
                        logger.trace(
                                "asymmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    if (enableSymmetricEncryption) {
                        response = getDecryptedResponse(response);
                        logger.trace("symmetric encryption enabled, encrypted request: " + response.toString());
                    }

                    Message msg = descriptorProtoMap.remove(response.getRequestId());
                    Message m = msg.getParserForType().parseFrom(response.getResponse());
                    callbackMap.remove(response.getRequestId()).run(m);

                    super.messageReceived(ctx, e);
                    stopWatch.stop();
                    logger.trace(stopWatch.shortSummary());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                    if (!standardExceptionHandling(ctx, e)) {
                        super.exceptionCaught(ctx, e);
                    }
                }
            });
            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
            return p;
        }
    });
}

From source file:com.gitblit.plugin.flowdock.FlowDock.java

FlowDock(IRuntimeManager runtimeManager) {
    this.runtimeManager = runtimeManager;
    this.taskPool = Executors.newCachedThreadPool();
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphore.java

@Test
public void testThreadedLeaseIncrease() throws Exception {
    final Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {/* w  ww  .j av  a 2  s  .co  m*/
        client.start();

        final SharedCount count = new SharedCount(client, "/foo/count", 1);
        count.start();

        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", count);

        ExecutorService service = Executors.newCachedThreadPool();

        final CountDownLatch latch = new CountDownLatch(1);
        Future<Object> future1 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS);
                Assert.assertNotNull(lease);
                latch.countDown();
                lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS);
                Assert.assertNotNull(lease);
                return null;
            }
        });
        Future<Object> future2 = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch.await(timing.seconds(), TimeUnit.SECONDS));
                timing.sleepABit(); // make sure second acquire is waiting
                Assert.assertTrue(count.trySetCount(2));
                return null;
            }
        });

        future1.get();
        future2.get();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.nts.alphamale.handler.ExecutorHandler.java

/**
 * parallel execute synchronous commandline
 * @param cmdList//from  w w  w . ja va  2s .c  om
 * @param timeoutSecond
 * @return
 */
public List<Map<String, Object>> executeParallel(List<CommandLine> cmdList, int timeoutSecond) {
    ExecutorService executor = Executors.newCachedThreadPool();
    List<Future<Map<String, Object>>> resultList;
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    List<SynchronousTask> taskList = new ArrayList<SynchronousTask>();
    for (CommandLine cmd : cmdList) {
        taskList.add(new SynchronousTask(cmd, timeoutSecond * 1000));
    }
    try {
        resultList = executor.invokeAll(taskList, timeoutSecond + 10, TimeUnit.SECONDS);
        for (Future<Map<String, Object>> result : resultList) {
            results.add(result.get());
        }
    } catch (InterruptedException e) {
        log.error(e.getMessage());
    } catch (ExecutionException e) {
        log.error(e.getMessage());
    }
    if (!executor.isShutdown()) {
        executor.shutdown();
    }
    return results;
}