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:com.ottogroup.bi.asap.pipeline.MicroPipelineManager.java

/**
 * Initializes the manager using the provided input
 * @param microPipelineFactory//from  ww  w  .  j  av  a  2s  . c  o  m
 */
public MicroPipelineManager(final MicroPipelineFactory microPipelineFactory) {
    this.factory = microPipelineFactory;
    this.pipelineThreadPool = Executors.newCachedThreadPool();
}

From source file:com.hs.mail.imap.server.ImapServer.java

public void afterPropertiesSet() throws Exception {
    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // Do not create many instances of Timer.
    // HashedWheelTimer creates a new thread whenever it is instantiated and
    // started. Therefore, you should make sure to create only one instance
    // and share it across your application.
    Timer timer = new HashedWheelTimer();
    // Set 30-minute read timeout.
    int timeout = (int) Config.getNumberProperty("imap_timeout", 1800);
    // timer must be shared.
    timeoutHandler = new ReadTimeoutHandler(timer, timeout);
    // prepare business logic handler
    handler = new ImapServerHandler();

    bootstrap.setPipelineFactory(createPipelineFactory());

    // Bind and start to accept incoming connections.
    InetSocketAddress endpoint = null;
    if (!StringUtils.isEmpty(bind) && !"*".equals(bind)) {
        InetAddress bindTo = InetAddress.getByName(bind);
        endpoint = new InetSocketAddress(bindTo, getPort());
    } else {/*from  w  ww  .ja  v  a 2  s  .  c  o  m*/
        endpoint = new InetSocketAddress(getPort());
    }
    bootstrap.bind(endpoint);

    StringBuilder logBuffer = new StringBuilder(64).append(getServiceType()).append(" started on port ")
            .append(getPort());
    Logger.getLogger("console").info(logBuffer.toString());
}

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

@Test
public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException {
    firstStep = newPipelineWithResponseBody("{id:123}");

    // use a synchronized set to collect the pipeline output from multiple threads
    Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>());

    // 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
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDown = new CountDownLatch(100);
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();/*from www  .  j a  v a  2  s . c o  m*/
            distinctOutputs.add(firstStep.getOutput().toBlocking().single());

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

    // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output
    assertEquals(1, distinctOutputs.size());
    JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(),
            JSONCompareMode.STRICT);
}

From source file:com.amazonaws.services.kinesis.multilang.MessageReaderTest.java

@Test
public void runLoopGoodInputTest() {
    String[] sequenceNumbers = new String[] { "123", "456", "789" };
    String[] responseFors = new String[] { "initialize", "processRecords", "processRecords", "shutdown" };
    InputStream stream = buildInputStreamOfGoodInput(sequenceNumbers, responseFors);
    MessageReader reader = new MessageReader().initialize(stream, shardId, new ObjectMapper(),
            Executors.newCachedThreadPool());

    for (String responseFor : responseFors) {
        StatusMessage statusMessage = null;
        try {// w  ww  . j ava  2s .  c  om
            Message message = reader.getNextMessageFromSTDOUT().get();
            if (message instanceof StatusMessage) {
                Assert.assertEquals("The status message's responseFor field should have been correct",
                        responseFor, ((StatusMessage) message).getResponseFor());
            }
        } catch (InterruptedException | ExecutionException e) {
            Assert.fail("There should have been a status message for " + responseFor);
        }
    }
}

From source file:com.kixeye.janus.client.http.async.AsyncHttpClient.java

/**
 * Creates an async http client./*ww  w .j  a  v  a  2 s  .c  o  m*/
 *
 * @param janus reference to Janus
 * @param numRetries number of retry attempts that should be made in the event of http request error. requests that fail to complete
 *                   are considered errors (ie. IOExceptions) and are eligible for retry. Requests that receive a response (regardless of http status) are
 *                   considered successful and are not eligible for retry.
 */
public AsyncHttpClient(Janus janus, int numRetries) {
    Preconditions.checkNotNull(janus, "'janus' is required but was null");
    Preconditions.checkArgument(numRetries >= 0, "'numRetries' must be >= 0");

    this.janus = janus;
    this.numRetries = numRetries;
    this.executor = Executors.newCachedThreadPool();
    this.httpClient = HttpAsyncClients.createDefault();

    this.httpClient.start();
}

From source file:com.serotonin.modbus4j.ip.listener.TcpListener.java

@Override
synchronized public void init() throws ModbusInitException {
    LOG.debug("Init TcpListener Port: " + ipParameters.getPort());
    executorService = Executors.newCachedThreadPool();
    startListener();/* ww  w. j a v a2  s. c  o m*/
    initialized = true;
    LOG.warn("Initialized Port: " + ipParameters.getPort());
}

From source file:com.twosigma.beakerx.evaluator.BaseEvaluator.java

public BaseEvaluator(String id, String sId, CellExecutor cellExecutor, TempFolderFactory tempFolderFactory,
        EvaluatorParameters evaluatorParameters, BeakerXClient beakerXClient,
        MagicCommandAutocompletePatterns autocompletePatterns) {
    shellId = id;/*from  w  w w .  ja  va 2  s . c  om*/
    sessionId = sId;
    executor = cellExecutor;
    tempFolder = tempFolderFactory.createTempFolder();
    this.beakerXClient = BeakerXClientManager.register(beakerXClient);
    this.autocompletePatterns = autocompletePatterns;
    outDir = getOrCreateFile(tempFolder.toString() + File.separator + "outDir").getPath();
    classPath = new Classpath();
    classPath.add(new PathToJar(outDir));
    inspect = new Inspect();
    executorService = Executors.newCachedThreadPool();
    executorBgkService = Executors.newCachedThreadPool();
    this.evaluatorParameters = evaluatorParameters;
    init(evaluatorParameters);
}

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

/**
 * execute asynchronous commandline//from  ww w  . ja  v  a2  s .c om
 * @param cmdList
 * @param timeout
 * @return
 */
public Map<String, Object> executeAsynchronous(CommandLine cmd, long timeout) {
    asynchExecutor = Executors.newCachedThreadPool();
    Future<Map<String, Object>> future = asynchExecutor
            .submit(new AsynchronousTask(cmd, ExecuteWatchdog.INFINITE_TIMEOUT));
    try {
        return future.get();
    } catch (InterruptedException e) {
        future.cancel(true);
    } catch (ExecutionException e) {
        log.error(e.getMessage());
    }
    return null;
}

From source file:aos.camel.JavaFutureTest.java

@Test
public void testFutureWithoutDone() throws Exception {
    // this is the task we want to execute async
    // usually the task is something that takes
    // some time to do
    Callable<String> task = new Callable<String>() {
        public String call() throws Exception {
            // do something that takes some time
            LOG.info("Starting to process task");
            Thread.sleep(5000);/*from   w  ww. j a v  a 2  s  . c  om*/
            LOG.info("Task is now done");
            return "Camel rocks";
        }
    };

    // this is the thread pool we will use
    ExecutorService executor = Executors.newCachedThreadPool();

    // now submit the task to the thread pool
    // and get the Future handle back so we can later get the result
    LOG.info("Submitting task to ExecutorService");
    Future<String> future = executor.submit(task);
    LOG.info("Task submitted and we got a Future handle");

    // instead of testing when we are done we can just get
    // the result and it will automatic wait until the task is done
    String answer = future.get();
    LOG.info("The answer is: " + answer);
}

From source file:com.linkedin.pinot.common.http.MultiGetRequestTest.java

@Test
public void testMultiGet() {
    MultiGetRequest mget = new MultiGetRequest(Executors.newCachedThreadPool(),
            new MultiThreadedHttpConnectionManager());
    List<String> urls = Arrays.asList("http://localhost:" + String.valueOf(portStart) + URI_PATH,
            "http://localhost:" + String.valueOf(portStart + 1) + URI_PATH,
            "http://localhost:" + String.valueOf(portStart + 2) + URI_PATH,
            // 2nd request to the same server
            "http://localhost:" + String.valueOf(portStart) + URI_PATH);
    // timeout value needs to be less than 5000ms set above for
    // third server
    final int requestTimeoutMs = 1000;
    CompletionService<GetMethod> completionService = mget.execute(urls, requestTimeoutMs);
    int success = 0;
    int errors = 0;
    int timeouts = 0;
    for (int i = 0; i < urls.size(); i++) {
        GetMethod getMethod = null;/*from  w ww  . j  a va 2s .c o  m*/
        try {
            getMethod = completionService.take().get();
            if (getMethod.getStatusCode() >= 300) {
                ++errors;
                Assert.assertEquals(getMethod.getResponseBodyAsString(), ERROR_MSG);
            } else {
                ++success;
                Assert.assertEquals(getMethod.getResponseBodyAsString(), SUCCESS_MSG);
            }

        } catch (InterruptedException e) {
            LOGGER.error("Interrupted", e);
            ++errors;
        } catch (ExecutionException e) {
            if (Throwables.getRootCause(e) instanceof SocketTimeoutException) {
                LOGGER.debug("Timeout");
                ++timeouts;
            } else {
                LOGGER.error("Error", e);
                ++errors;
            }
        } catch (IOException e) {
            ++errors;
        }
    }

    Assert.assertEquals(2, success);
    Assert.assertEquals(1, errors);
    Assert.assertEquals(1, timeouts);
}