Example usage for java.util.concurrent ThreadPoolExecutor prestartAllCoreThreads

List of usage examples for java.util.concurrent ThreadPoolExecutor prestartAllCoreThreads

Introduction

In this page you can find the example usage for java.util.concurrent ThreadPoolExecutor prestartAllCoreThreads.

Prototype

public int prestartAllCoreThreads() 

Source Link

Document

Starts all core threads, causing them to idly wait for work.

Usage

From source file:com.espertech.esper.core.thread.ThreadingServiceImpl.java

private ThreadPoolExecutor getThreadPool(String engineURI, String name, BlockingQueue<Runnable> queue,
        int numThreads) {
    if (log.isInfoEnabled()) {
        log.info("Starting pool " + name + " with " + numThreads + " threads");
    }//w  ww.j  a  va2  s. com

    if (engineURI == null) {
        engineURI = "default";
    }

    String threadGroupName = "com.espertech.esper." + engineURI + "-" + name;
    ThreadGroup threadGroup = new ThreadGroup(threadGroupName);
    ThreadPoolExecutor pool = new ThreadPoolExecutor(numThreads, numThreads, 1, TimeUnit.SECONDS, queue,
            new EngineThreadFactory(engineURI, name, threadGroup, Thread.NORM_PRIORITY));
    pool.prestartAllCoreThreads();

    return pool;
}

From source file:bigbird.benchmark.HttpBenchmark.java

public void execute() {
    params = getHttpParams(socketTimeout, useHttp1_0);

    for (RequestGenerator g : requestGenerators) {
        g.setParameters(params);//from w w w. j a v  a  2 s .  c  om
    }

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

    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                public Thread newThread(Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    BenchmarkWorker[] workers = new BenchmarkWorker[threads];
    for (int i = 0; i < threads; i++) {
        workers[i] = new BenchmarkWorker(params, verbosity, requestGenerators[i], host, requests, keepAlive);
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < threads) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }

    workerPool.shutdown();
    ResultProcessor.printResults(workers, host, url.toString(), contentLength);
}

From source file:org.apache.http.contrib.benchmark.HttpBenchmark.java

private void execute() {

    prepare();/*from w  w w.j  a v  a 2s  .  com*/

    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                public Thread newThread(Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    BenchmarkWorker[] workers = new BenchmarkWorker[threads];
    for (int i = 0; i < threads; i++) {
        workers[i] = new BenchmarkWorker(params, verbosity, request[i], host, requests, keepAlive);
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < threads) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }

    workerPool.shutdown();
    ResultProcessor.printResults(workers, host, url.toString(), contentLength);
}

From source file:org.apache.http.benchmark.HttpBenchmark.java

public String execute() throws Exception {

    prepare();//from  w  w  w. ja  v  a 2s .  c o m

    ThreadPoolExecutor workerPool = new ThreadPoolExecutor(config.getThreads(), config.getThreads(), 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                public Thread newThread(Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new BenchmarkWorker(params, config.getVerbosity(), request[i], host, config.getRequests(),
                config.isKeepAlive(), config.isDisableSSLVerification(), config.getTrustStorePath(),
                config.getTrustStorePassword(), config.getIdentityStorePath(),
                config.getIdentityStorePassword());
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < config.getThreads()) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }

    workerPool.shutdown();
    return ResultProcessor.printResults(workers, host, config.getUrl().toString(), contentLength);
}

From source file:org.apache.hc.core5.http.benchmark.HttpBenchmark.java

public Results doExecute() throws Exception {

    final URL url = config.getUrl();
    final long endTime = System.currentTimeMillis() + config.getTimeLimit() * 1000;
    final HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    final ThreadPoolExecutor workerPool = new ThreadPoolExecutor(config.getThreads(), config.getThreads(), 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {

                @Override//from w ww  . j  a  va  2 s . co  m
                public Thread newThread(final Runnable r) {
                    return new Thread(r, "ClientPool");
                }

            });
    workerPool.prestartAllCoreThreads();

    SocketFactory socketFactory = null;
    if ("https".equals(host.getSchemeName())) {
        final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.setProtocol("SSL");
        if (config.isDisableSSLVerification()) {
            sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }

            });
        } else if (config.getTrustStorePath() != null) {
            sslContextBuilder.loadTrustMaterial(new File(config.getTrustStorePath()),
                    config.getTrustStorePassword() != null ? config.getTrustStorePassword().toCharArray()
                            : null);
        }
        if (config.getIdentityStorePath() != null) {
            sslContextBuilder.loadKeyMaterial(new File(config.getIdentityStorePath()),
                    config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray()
                            : null,
                    config.getIdentityStorePassword() != null ? config.getIdentityStorePassword().toCharArray()
                            : null);
        }
        final SSLContext sslContext = sslContextBuilder.build();
        socketFactory = sslContext.getSocketFactory();
    }

    final BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new BenchmarkWorker(host, createRequest(host), socketFactory, config);
        workerPool.execute(workers[i]);
    }

    while (workerPool.getCompletedTaskCount() < config.getThreads()) {
        Thread.yield();
        try {
            Thread.sleep(1000);
        } catch (final InterruptedException ignore) {
        }
        if (config.getTimeLimit() != -1 && System.currentTimeMillis() > endTime) {
            for (int i = 0; i < workers.length; i++) {
                workers[i].setShutdownSignal();
            }
        }
    }

    workerPool.shutdown();
    return ResultProcessor.collectResults(workers, host, config.getUrl().toString());
}

From source file:com.attribyte.essem.ApplicationCache.java

ApplicationCache(final AsyncClient client, final RequestOptions requestOptions, final ESEndpoint esEndpoint,
        final Logger logger) {

    this.client = client;
    this.requestOptions = requestOptions;
    this.esEndpoint = esEndpoint;
    this.logger = logger;

    final BlockingQueue<Runnable> requestQueue = new ArrayBlockingQueue<>(4096);
    final Gauge<Integer> requestQueueSize = new Gauge<Integer>() {
        @Override//  w w w . jav  a  2  s  .  c o  m
        public Integer getValue() {
            return requestQueue.size();
        }
    };

    final ThreadPoolExecutor requestExecutor = new ThreadPoolExecutor(2, 8, 5L, TimeUnit.MINUTES, requestQueue,
            new ThreadFactoryBuilder().setNameFormat("application-cache-%d").build());
    requestExecutor.prestartAllCoreThreads();

    final Counter rejectedRequests = new Counter();
    requestExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
            rejectedRequests.inc();
        }
    });
    this.requestExecutor = MoreExecutors
            .listeningDecorator(MoreExecutors.getExitingExecutorService(requestExecutor));

    this.appRequestTimer = new Timer();
    this.appRequestErrors = new Counter();

    this.nameRequestTimer = new Timer();
    this.nameRequestErrors = new Counter();

    this.statsRequestTimer = new Timer();
    this.statsRequestErrors = new Counter();

    Gauge<Integer> appCacheSize = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return appCache.size();
        }
    };

    this.metrics = ImmutableMap.<String, com.codahale.metrics.Metric>builder()
            .put("request-queue-size", requestQueueSize).put("rejected-background-requests", rejectedRequests)
            .put("app-requests", appRequestTimer).put("app-request-errors", appRequestErrors)
            .put("name-requests", nameRequestTimer).put("name-request-errors", nameRequestErrors)
            .put("app-cache-size", appCacheSize).put("stats-requests", statsRequestTimer)
            .put("stats-request-errors", statsRequestErrors).build();
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private ThreadPoolExecutor postProcess() {
    while (!this.samplingFinished) {
        try {/*from w  ww  . j ava  2s  . c  om*/
            Thread.currentThread();
            Thread.sleep(100);
        } catch (final InterruptedException e) {
        }
    }

    final LinkedBlockingQueue<Runnable> processingQueue = new LinkedBlockingQueue<Runnable>(
            this.profilingQueue);

    final int nThreads = Runtime.getRuntime().availableProcessors();
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
            processingQueue);
    executor.prestartAllCoreThreads();

    return executor;
}

From source file:com.splicemachine.derby.stream.control.ControlDataSet.java

@Override
public DataSet<V> union(DataSet<V> dataSet) {
    ThreadPoolExecutor tpe = null;
    try {//from   ww  w .j  av  a  2  s.co  m

        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("union-begin-query-%d")
                .setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        e.printStackTrace();
                    }
                }).build();
        tpe = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory,
                new ThreadPoolExecutor.CallerRunsPolicy());
        tpe.allowCoreThreadTimeOut(false);
        tpe.prestartAllCoreThreads();
        Future<Iterator<V>> leftSideFuture = tpe.submit(new NonLazy(iterator));
        Future<Iterator<V>> rightSideFuture = tpe.submit(new NonLazy(((ControlDataSet<V>) dataSet).iterator));

        return new ControlDataSet<>(Iterators.concat(leftSideFuture.get(), rightSideFuture.get()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (tpe != null)
            tpe.shutdown();
    }
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private ThreadPoolExecutor createExecutor(BlockingQueue<Runnable> workQueue) {
    final AtomicInteger nextThreadNo = new AtomicInteger(0);

    final ThreadPoolExecutor executor = new ThreadPoolExecutor(//
            BenchmarkTest.THREAD_COUNT, BenchmarkTest.THREAD_COUNT, // min max threads
            0L, TimeUnit.MILLISECONDS, // the keep alive time - hold it forever
            workQueue, new ThreadFactory() {

                @Override//w w  w  . j a v  a 2  s . c o  m
                public Thread newThread(Runnable r) {
                    final Thread t = new Thread(r);
                    t.setDaemon(true);
                    t.setPriority(Thread.NORM_PRIORITY);
                    t.setName("Benchmark-" + nextThreadNo.get());

                    BenchmarkTest.this.threadIds[nextThreadNo.getAndIncrement()] = t.getId();

                    return t;
                }
            });

    executor.prestartAllCoreThreads();

    return executor;
}