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.intuit.tank.proxy.Main.java

public void startHttpServer() throws IOException {
    InetSocketAddress addr = new InetSocketAddress(apiPort);
    HttpServer server = HttpServer.create(addr, 0);

    HttpHandler handler = new HttpHandler() {
        public void handle(HttpExchange exchange) throws IOException {
            String requestMethod = exchange.getRequestMethod();
            URI requestURI = exchange.getRequestURI();
            String msg = "unknown path";
            if (requestMethod.equalsIgnoreCase("GET")) {
                // Thread t = null;
                if (requestURI.getPath().startsWith("/start")) {
                    msg = "starting proxy on port " + port + " outputting to " + dumpFileName;
                    // t = new Thread(new Runnable() {
                    // @Override
                    // public void run() {
                    start();//from   w w w.j  a  v  a2s .  co m
                    // }
                    // });
                } else if (requestURI.getPath().startsWith("/stop")) {
                    msg = "stopping proxy and finalizing output in file " + dumpFileName;
                    // t = new Thread(new Runnable() {
                    // @Override
                    // public void run() {
                    stop();
                    // }
                    // });
                } else if (requestURI.getPath().startsWith("/quit")) {
                    msg = "quitting proxy and finalizing output in file " + dumpFileName;
                    // t = new Thread(new Runnable() {
                    // @Override
                    // public void run() {
                    quit();
                    // }
                    // });
                }
                byte[] bytes = msg.getBytes();
                Headers responseHeaders = exchange.getResponseHeaders();
                responseHeaders.set("Content-Type", "text/plain");
                exchange.sendResponseHeaders(200, bytes.length);
                OutputStream responseBody = exchange.getResponseBody();

                responseBody.write(bytes);
                responseBody.close();
                // if (t != null) {
                // t.start();
                // }
            }
        }
    };

    server.createContext("/", handler);
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
    System.out.println("Server is listening on port " + apiPort);
}

From source file:com.pyj.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//  w w  w  .j  a v a  2  s.c o m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);
    // ?cookie
    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    // httpParams.setParameter(ClientPNames.COOKIE_POLICY, "hupu.com");
    httpParams.setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
        httpParams.setParameter("Connection", "close");
    }
    // HttpProtocolParams.setUserAgent(httpParams,
    // String.format("android-async-http/%s (http://loopj.com/android-async-http)",
    // VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // SSLSocketFactory ssl=getSSLSocketFactory();
    // schemeRegistry.register(new Scheme("https", ssl, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            if (!request.containsHeader(""))
                for (String header : clientHeaderMap.keySet()) {
                    request.addHeader(header, clientHeaderMap.get(header));
                }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    // HupuLog.d("ResponseInterceptor",
                    // "key="+element.getName()+" value="+element.getValue());
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        //                     HupuLog.d("ResponseInterceptor", "gzip");
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        // continue;
                    }

                }
            }
            Header[] headers = response.getHeaders(HEADER_DATE);
            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    if (headers[i].getName().equalsIgnoreCase(HEADER_DATE)) {
                        Date date = new java.util.Date(headers[i].getValue());
                        today = date.getTime();
                        // Calendar cal = new GregorianCalendar();
                    }
                }
            }

        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();

    // CookieStore cookieStore = new BasicCookieStore();
    // setCookieStore(cookieStore);

}

From source file:org.jboss.aerogear.sync.server.netty.DiffSyncHandlerTest.java

@Test
public void addDocumentWithoutContentConcurrent() throws Exception {
    final ExecutorService executorService = Executors.newCachedThreadPool();
    final int iterations = 100;
    final CountDownLatch await = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(iterations);
    final String content = "You shall not pass!";
    final List<Future<PatchMessage<DiffMatchPatchEdit>>> futures = new ArrayList<Future<PatchMessage<DiffMatchPatchEdit>>>();
    final String client2Id = "client2";
    for (int i = 0; i < iterations; i++) {
        final String docId = UUID.randomUUID().toString();
        final ServerInMemoryDataStore<String, DiffMatchPatchEdit> dataStore = new ServerInMemoryDataStore<String, DiffMatchPatchEdit>();
        final EmbeddedChannel channel1 = embeddedChannel(dataStore);
        final EmbeddedChannel channel2 = embeddedChannel(dataStore);
        executorService.submit(new AddDocumentTask(channel1, docId, "client1", content, await, latch));
        final Future<PatchMessage<DiffMatchPatchEdit>> future = executorService
                .submit(new AddDocumentTask(channel2, docId, client2Id, null, await, latch));
        futures.add(future);//from w w  w . j a  va  2s .  c  o m
    }
    await.countDown();
    latch.await();
    for (Future<PatchMessage<DiffMatchPatchEdit>> future : futures) {
        final PatchMessage<DiffMatchPatchEdit> patchMessage = future.get();
        assertThat(patchMessage.clientId(), equalTo(client2Id));
        // patchMessage can be empty if there is not yet and underlying document in the data store.
        // in our case this means that the first thread has not yet been executed.
        if (!patchMessage.edits().isEmpty()) {
            assertThat(patchMessage.edits().size(), is(1));
            final DiffMatchPatchEdit edit = patchMessage.edits().peek();
            assertThat(edit.serverVersion(), is(1L));
            assertThat(edit.diff().diffs().get(0).operation(), is(Operation.UNCHANGED));
            assertThat(edit.diff().diffs().get(0).text(), equalTo(content));
        }
    }
    executorService.shutdown();
}

From source file:com.enjoy.nerd.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w w w  .  j av a 2s.co m
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, String.format("qqlive-async-http/%s", VERSION));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();

    mBasicHttpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);

    //????????location?CircularRedirectException?ClientProtocolException modified by danccyai 2014-06-02
    httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });
    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.test.HibernateDerbyLockingTest.java

public void runTest(final SessionFactory sessionFactory) throws Exception {
    Person person = new Person();

    Session session = sessionFactory.openSession();
    session.save(person);//from  ww w .j  a v  a 2 s. co m
    session.flush();
    session.close();

    final String id = person.getId();
    final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

    ExecutorService executorService = Executors.newCachedThreadPool();
    Future<?> submit = executorService.submit(new Runnable() {
        public void run() {
            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            session.load(Person.class, id, LockMode.UPGRADE);
            try {
                Thread.sleep(2000);
            } catch (Throwable t) {
            }
            System.out.println("one");
            queue.add("one");
            try {
                Thread.sleep(500);
            } catch (Throwable t) {
            }
            transaction.commit();
            session.flush();
            session.close();
        }
    });
    Thread.sleep(500);
    Future<?> submit2 = executorService.submit(new Runnable() {
        public void run() {
            Session session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            session.load(Person.class, id, LockMode.UPGRADE);
            queue.add("two");
            System.out.println("two");
            transaction.commit();
            session.flush();
            session.close();
        }
    });
    submit.get();
    submit2.get();
    assertEquals("one", queue.poll(3, TimeUnit.SECONDS));
    assertEquals("two", queue.poll(3, TimeUnit.SECONDS));
}

From source file:com.jagornet.dhcp.client.ClientSimulatorV6.java

/**
 * Start sending DHCPv6 SOLICITs./*from   w w w. j ava  2s .  c o m*/
 */
public void start() {
    DatagramChannelFactory factory = new OioDatagramChannelFactory(Executors.newCachedThreadPool());

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

    ChannelPipeline pipeline = Channels.pipeline();
    pipeline.addLast("logger", new LoggingHandler());
    pipeline.addLast("encoder", new DhcpV6ChannelEncoder());
    pipeline.addLast("decoder", new DhcpV6ChannelDecoder(client, false));
    pipeline.addLast("executor",
            new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16, 1048576, 1048576)));
    pipeline.addLast("handler", this);

    channel = factory.newChannel(pipeline);
    channel.getConfig().setNetworkInterface(mcastNetIf);
    channel.bind(client);

    for (int i = 1; i <= numRequests; i++) {
        executor.execute(new ClientMachine(i));
    }

    synchronized (syncDone) {
        long ms = timeout * 1000;
        try {
            log.info("Waiting total of " + timeout + " milliseconds for completion");
            syncDone.wait(ms);
        } catch (InterruptedException ex) {
            log.error("Interrupted", ex);
        }
    }

    log.info("Complete: solicitsSent=" + solicitsSent + " advertisementsReceived=" + advertisementsReceived
            + " requestsSent=" + requestsSent + " requestRepliesReceived=" + requestRepliesReceived
            + " releasesSent=" + releasesSent + " releaseRepliesReceived=" + releaseRepliesReceived
            + " elapsedTime=" + (endTime - startTime) + "ms");

    log.info("Shutting down executor...");
    executor.shutdownNow();
    log.info("Closing channel...");
    channel.close();
    log.info("Done.");
    if ((solicitsSent.get() == advertisementsReceived.get())
            && (requestsSent.get() == requestRepliesReceived.get())
            && (releasesSent.get() == releaseRepliesReceived.get())) {

        System.exit(0);
    } else {
        System.exit(1);
    }
}

From source file:vn.topmedia.monitor.MonitorAppender.java

/**
 * Submit the required number of senders into the pool.
 *//*from   w w w  .j  a  va 2 s.c o  m*/
protected void startSenders() {
    senderPool = Executors.newCachedThreadPool();
    for (int i = 0; i < senderPoolSize; i++) {
        senderPool.submit(new EventSender());
    }
}

From source file:com.serotonin.bacnet4j.LocalDevice.java

public synchronized void initialize() throws Exception {
    if (executorService == null) {
        executorService = Executors.newCachedThreadPool();
        ownsExecutorService = true;//from   w  ww  . ja  v  a 2  s. com
    } else
        ownsExecutorService = false;
    // For the async handler
    //eventHandler.initialize(executorService);
    transport.initialize();
    initialized = true;
}

From source file:com.linkedin.pinot.transport.netty.NettySingleConnectionIntegrationTest.java

/**
 * This test attempts to use the connection mechanism the same way as ScatterGatherImpl.SingleRequestHandler does.
 *//*  w  ww.  ja v  a  2  s.  c o m*/
@SuppressWarnings("unchecked")
@Test
public void testServerShutdownLeak() throws Exception {
    PooledNettyClientResourceManager resourceManager = new PooledNettyClientResourceManager(
            new NioEventLoopGroup(), new HashedWheelTimer(), new NettyClientMetrics(null, "abc"));
    ExecutorService executorService = Executors.newCachedThreadPool();
    ScheduledExecutorService timeoutExecutor = new ScheduledThreadPoolExecutor(5);

    KeyedPool<PooledNettyClientResourceManager.PooledClientConnection> keyedPool = new KeyedPoolImpl<>(
            /*minSize=*/2, /*maxSize=*/3, /*idleTimeoutMs=*/100000L, /*maxPending=*/1, resourceManager,
            timeoutExecutor, executorService, new MetricsRegistry());
    resourceManager.setPool(keyedPool);

    try {
        keyedPool.start();

        // The act of calling checkoutObject() creates a new AsyncPool and places a request for a new connection
        // NOTE: since no connections are available in the beginning, and the min connections are still being filled, we
        // always end up creating one more connection than the min connections
        Assert.assertNotNull(keyedPool.checkoutObject(_clientServer).getOne());

        // Use reflection to get the pool and the waiters queue
        Field keyedPoolField = KeyedPoolImpl.class.getDeclaredField("_keyedPool");
        keyedPoolField.setAccessible(true);
        Map<ServerInstance, AsyncPool<NettyClientConnection>> poolMap = (Map<ServerInstance, AsyncPool<NettyClientConnection>>) keyedPoolField
                .get(keyedPool);
        AsyncPool<NettyClientConnection> pool = poolMap.get(_clientServer);
        Field waitersField = AsyncPoolImpl.class.getDeclaredField("_waiters");
        waitersField.setAccessible(true);
        LinkedDequeue waitersQueue = (LinkedDequeue) waitersField.get(pool);

        // Make sure the min pool size is filled out
        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);

        PoolStats stats = pool.getStats();
        Assert.assertEquals(stats.getPoolSize(), 3);
        Assert.assertEquals(stats.getIdleCount(), 2);
        Assert.assertEquals(stats.getCheckedOut(), 1);
        Assert.assertEquals(waitersQueue.size(), 0);

        // Get two more connections to the server and leak them
        Assert.assertNotNull(keyedPool.checkoutObject(_clientServer).getOne());
        Assert.assertNotNull(keyedPool.checkoutObject(_clientServer).getOne());
        stats = pool.getStats();
        Assert.assertEquals(stats.getPoolSize(), 3);
        Assert.assertEquals(stats.getIdleCount(), 0);
        Assert.assertEquals(stats.getCheckedOut(), 3);
        Assert.assertEquals(waitersQueue.size(), 0);

        // Try to get one more connection
        // We should get an exception because we don't have a free connection to the server
        ServerResponseFuture<PooledNettyClientResourceManager.PooledClientConnection> serverResponseFuture = keyedPool
                .checkoutObject(_clientServer);
        try {
            serverResponseFuture.getOne(1, TimeUnit.SECONDS);
            Assert.fail("Get connection even no connections available");
        } catch (TimeoutException e) {
            // PASS
        }
        stats = pool.getStats();
        Assert.assertEquals(stats.getPoolSize(), 3);
        Assert.assertEquals(stats.getIdleCount(), 0);
        Assert.assertEquals(stats.getCheckedOut(), 3);
        Assert.assertEquals(waitersQueue.size(), 1);
        serverResponseFuture.cancel(true);
        Assert.assertEquals(waitersQueue.size(), 0);

        // If the server goes down, we should release all 3 connections and be able to get new connections
        closeServerConnection();
        setUp();
        stats = pool.getStats();
        Assert.assertEquals(stats.getPoolSize(), 2);
        Assert.assertEquals(stats.getIdleCount(), 2);

        // Try to get 3 new connections
        for (int i = 0; i < 3; i++) {
            Assert.assertNotNull(keyedPool.checkoutObject(_clientServer).getOne());
        }
    } finally {
        keyedPool.shutdown();
        executorService.shutdown();
        timeoutExecutor.shutdown();
    }
}

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

@Test
public void test2ClientsZeroOneDenseModelWithMixCanceling() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);/*from  ww  w .  j a v a2s  .  c  o  m*/

    waitForState(server, ServerState.RUNNING);

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