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:ddf.metrics.collector.rrd4j.RrdJmxCollector.java

/**
 * Initialization when the JmxCollector is created. Called by blueprint.
 *//*from  w  w  w . j a v a2  s.  c  om*/
public void init() {
    LOGGER.trace("ENTERING: init() for metric {}", metricName);

    if (executorPool == null) {
        executorPool = Executors.newCachedThreadPool();
    }

    // Creating JmxCollector can be time consuming,
    // so do this in a separate thread to prevent holding up creation
    // of Sources or the Catalog
    final Runnable jmxCollectorCreator = new Runnable() {
        public void run() {
            try {
                configureCollector();
            } catch (CollectorException e) {
                // Ignore, it has already been logged
            } catch (IOException e) {
                // Ignore, it has already been logged
            }
        }
    };

    LOGGER.debug("Start configureCollector thread for JmxCollector {}", mbeanAttributeName);
    executorPool.execute(jmxCollectorCreator);

    LOGGER.trace("EXITING: init()");
}

From source file:ru.jts_dev.authserver.config.AuthIntegrationConfig.java

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

From source file:com.liferay.sync.engine.session.Session.java

public Session(URL url, String oAuthConsumerKey, String oAuthConsumerSecret, String oAuthToken,
        String oAuthTokenSecret, boolean trustSelfSigned, int maxConnections) {

    if (maxConnections == Integer.MAX_VALUE) {
        _executorService = Executors.newCachedThreadPool();
    } else {//ww  w .  jav  a  2 s  .com
        _executorService = Executors.newFixedThreadPool(maxConnections);
    }

    HttpClientBuilder httpClientBuilder = createHttpClientBuilder(trustSelfSigned, maxConnections);

    httpClientBuilder.setConnectionManager(_getHttpClientConnectionManager(trustSelfSigned));

    _httpClient = httpClientBuilder.build();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    _oAuthConsumer = new CommonsHttpOAuthConsumer(oAuthConsumerKey, oAuthConsumerSecret);

    _oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret);

    _oAuthEnabled = true;
}

From source file:com.dangdang.ddframe.job.internal.job.dataflow.AbstractDataFlowElasticJob.java

@Override
public ExecutorService getExecutorService() {
    return Executors.newCachedThreadPool();
}

From source file:mitm.common.tools.SendMail.java

private void sendMultiThreaded(final MailTransport mailSender, final MimeMessage message,
        final Address[] recipients) throws InterruptedException {
    ExecutorService threadPool = Executors.newCachedThreadPool();

    final Semaphore semaphore = new Semaphore(threads, true);

    final long startTime = System.currentTimeMillis();

    for (int i = 1; i <= count; i++) {
        long threadStart = System.currentTimeMillis();

        semaphore.acquireUninterruptibly();

        threadPool.execute(new Runnable() {
            @Override/*from   w  w w  . j av  a  2 s.  c  o  m*/
            public void run() {
                try {
                    MimeMessage clone = MailUtils.cloneMessage(message);

                    int sent = sentCount.incrementAndGet();

                    if (uniqueFrom) {
                        Address[] froms = clone.getFrom();

                        if (froms != null && froms.length > 0) {
                            clone.setFrom(
                                    new InternetAddress(sent + EmailAddressUtils.getEmailAddress(froms[0])));
                        }
                    }

                    mailSender.sendMessage(clone, recipients);

                    long timePassed = DateTimeUtils
                            .millisecondsToSeconds(System.currentTimeMillis() - startTime);

                    StrBuilder sb = new StrBuilder();

                    sb.append("Message\t" + sent + "\tsent.");

                    if (timePassed > 0) {
                        float msgPerSec = (float) sent / timePassed;

                        sb.append("\tmessages/second\t" + String.format("%.2f", msgPerSec));
                    }

                    logger.info(sb.toString());
                } catch (MessagingException e) {
                    logger.error("Error sending message.", e);
                } finally {
                    semaphore.release();
                }
            }
        });

        if (forceQuit.get()) {
            break;
        }

        if (throtllingSemaphore != null) {
            /* for throttling the sending of emails */
            throtllingSemaphore.acquire();
        } else {
            /* no throttling so use delay */
            long sleepTime = delay - (System.currentTimeMillis() - threadStart);

            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
        }
    }

    threadPool.shutdown();
    threadPool.awaitTermination(30, TimeUnit.SECONDS);

    waitForReceiveThreads();

    logger.info("Total sent: " + sentCount.intValue() + ". Total time: "
            + DateTimeUtils.millisecondsToSeconds(System.currentTimeMillis() - startTime) + " (sec.)");
}

From source file:com.jagornet.dhcpv6.client.TestV4Client.java

/**
 * Start sending DHCPv4 DISCOVERs.// w  ww  .  j  a v  a 2 s  . co  m
 */
public void start() {
    DatagramChannelFactory factory = new NioDatagramChannelFactory(Executors.newCachedThreadPool());

    InetSocketAddress server = new InetSocketAddress(serverAddr, serverPort);
    InetSocketAddress client = new InetSocketAddress(clientPort);

    ChannelPipeline pipeline = Channels.pipeline();
    pipeline.addLast("logger", new LoggingHandler());
    pipeline.addLast("encoder", new DhcpV4ChannelEncoder());
    pipeline.addLast("decoder", new DhcpV4ChannelDecoder(client, false));
    pipeline.addLast("handler", this);

    channel = factory.newChannel(pipeline);
    channel.bind(client);

    List<DhcpV4Message> requestMsgs = buildRequestMessages();

    for (DhcpV4Message msg : requestMsgs) {
        executor.execute(new RequestSender(msg, server));
    }

    long ms = 0;
    if (rapidCommit)
        ms = requestMsgs.size() * 200;
    else
        ms = requestMsgs.size() * 20;

    synchronized (requestMap) {
        try {
            log.info("Waiting total of " + ms + " milliseconds for completion");
            //              requestMap.wait(ms);
            requestMap.wait();
        } catch (InterruptedException ex) {
            log.error("Interrupted", ex);
        }
    }

    log.info("Successfully processed " + successCnt + " of " + requestsSent + " messages in "
            + (endTime - startTime) + " milliseconds");

    log.info("Shutting down executor...");
    executor.shutdownNow();
    log.info("Closing channel...");
    channel.close();
    log.info("Done.");
    System.exit(0);
}

From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java

@Test(timeout = 5000)
public void validateInfiniteJavaContainerLaunchForcedShutdown() throws Exception {
    final YarnApplication<Void> yarnApplication = YarnAssembly
            .forApplicationContainer(InfiniteContainer.class, ByteBuffer.wrap("Hello".getBytes()))
            .containerCount(4).memory(512).withApplicationMaster().maxAttempts(2).priority(2)
            .build("sample-yarn-application");
    ExecutorService executor = Executors.newCachedThreadPool();
    executor.execute(new Runnable() {
        @Override//from w  w  w  .  j  av  a 2 s. co  m
        public void run() {
            yarnApplication.launch();
        }
    });
    Thread.sleep(4000);
    assertTrue(yarnApplication.isRunning());
    yarnApplication.terminate();
    assertFalse(yarnApplication.isRunning());
    executor.shutdown();
}

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

@Override
synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException {

    if (!connected) {
        LOG.debug("No connection in Port: " + ipParameters.getPort());
        throw new ModbusTransportException(new Exception("TCP Listener has no active connection!"),
                request.getSlaveId());//  w w w . j  av  a 2s.  c o m
    }

    if (!initialized) {
        LOG.debug("Listener already terminated " + ipParameters.getPort());
        return null;
    }

    // Wrap the modbus request in a ip request.
    OutgoingRequestMessage ipRequest;
    if (ipParameters.isEncapsulated()) {
        ipRequest = new EncapMessageRequest(request);
        StringBuilder sb = new StringBuilder();
        for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) {
            sb.append(String.format("%02X ", b));
        }
        LOG.debug("Encap Request: " + sb.toString());
    } else {
        ipRequest = new XaMessageRequest(request, getNextTransactionId());
        StringBuilder sb = new StringBuilder();
        for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) {
            sb.append(String.format("%02X ", b));
        }
        LOG.debug("Xa Request: " + sb.toString());
    }

    // Send the request to get the response.
    IpMessageResponse ipResponse;
    try {
        // Send data via handler!
        handler.conn.DEBUG = true;
        ipResponse = (IpMessageResponse) handler.conn.send(ipRequest);
        if (ipResponse == null) {
            throw new ModbusTransportException(new Exception("No valid response from slave!"),
                    request.getSlaveId());
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, ipResponse.getMessageData().length)) {
            sb.append(String.format("%02X ", b));
        }
        LOG.debug("Response: " + sb.toString());
        return ipResponse.getModbusResponse();
    } catch (Exception e) {
        LOG.debug(e.getLocalizedMessage() + ",  Port: " + ipParameters.getPort() + ", retries: " + retries);
        if (retries < 10 && !e.getLocalizedMessage().contains("Broken")) {
            retries++;
        } else {
            /*
             * To recover from a Broken Pipe, the only way is to restart serverSocket
             */
            LOG.debug("Restarting Socket,  Port: " + ipParameters.getPort() + ", retries: " + retries);

            // Close the serverSocket first to prevent new messages.
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e2) {
                LOG.debug("Error closing socket" + e2.getLocalizedMessage(), e);
                getExceptionHandler().receivedException(e2);
            }

            // Close all open connections.
            if (handler != null) {
                handler.closeConnection();
                terminateListener();
            }

            if (!initialized) {
                LOG.debug("Listener already terminated " + ipParameters.getPort());
                return null;
            }

            executorService = Executors.newCachedThreadPool();
            try {
                startListener();
            } catch (Exception e2) {
                LOG.warn("Error trying to restart socket" + e2.getLocalizedMessage(), e);
                throw new ModbusTransportException(e2, request.getSlaveId());
            }
            retries = 0;
        }
        LOG.warn("Error sending request,  Port: " + ipParameters.getPort() + ", msg: " + e.getMessage());
        // Simple send error!
        throw new ModbusTransportException(e, request.getSlaveId());
    }
}

From source file:net.joshdevins.rabbitmq.client.ha.HaConnectionFactory.java

public HaConnectionFactory(final ConnectionParameters params) {
    super(params);

    executorService = Executors.newCachedThreadPool();
    setDefaultRetryStrategy();//  www  .  ja v a 2  s .  c  om

    // TODO: Should we use a concurrent instance or sync access to this Set?
    listeners = new HashSet<HaConnectionListener>();
}

From source file:tw.edu.sju.ee.eea.module.iepe.project.window.IepeRealtimeSpectrumElement.java

private void initFX(JFXPanel fxPanel) {
    // This method is invoked on the JavaFX thread
    Scene scene = createScene();/*from   ww  w.j a va  2 s.c o m*/
    fxPanel.setScene(scene);

    //-- Prepare Executor Services
    executor = Executors.newCachedThreadPool();
    addToQueue = new AddToQueue();
    executor.execute(addToQueue);
    //-- Prepare Timeline
    prepareTimeline();
}