Example usage for java.util.concurrent ThreadPoolExecutor ThreadPoolExecutor

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

Introduction

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

Prototype

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) 

Source Link

Document

Creates a new ThreadPoolExecutor with the given initial parameters and Executors#defaultThreadFactory default thread factory .

Usage

From source file:org.apache.axis2.transport.jms.JMSListener.java

/**
 * Start this JMS Listener (Transport Listener)
 *
 * @throws AxisFault// w ww  . ja  v a 2  s  .  c  o m
 */
public void start() throws AxisFault {
    // create thread pool of workers
    workerPool = new ThreadPoolExecutor(1, WORKERS_MAX_THREADS, WORKER_KEEP_ALIVE, TIME_UNIT,
            new LinkedBlockingQueue(), new org.apache.axis2.util.threadpool.DefaultThreadFactory(
                    new ThreadGroup("JMS Worker thread group"), "JMSWorker"));

    Iterator iter = connectionFactories.values().iterator();
    while (iter.hasNext()) {
        JMSConnectionFactory conFac = (JMSConnectionFactory) iter.next();
        JMSMessageReceiver msgRcvr = new JMSMessageReceiver(conFac, workerPool, configCtx);

        try {
            conFac.listen(msgRcvr);
        } catch (JMSException e) {
            handleException("Error starting connection factory : " + conFac.getName(), e);
        }
    }
}

From source file:com.facebook.FacebookSdk.java

/**
 * Returns the Executor used by the SDK for non-AsyncTask background work.
 *
 * By default this uses AsyncTask Executor via reflection if the API level is high enough.
 * Otherwise this creates a new Executor with defaults similar to those used in AsyncTask.
 *
 * @return an Executor used by the SDK.  This will never be null.
 *//*from w  w w .j a v a  2  s .  c  o  m*/
public static Executor getExecutor() {
    synchronized (LOCK) {
        if (FacebookSdk.executor == null) {
            Executor executor = getAsyncTaskExecutor();
            if (executor == null) {
                executor = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE,
                        DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY);
            }
            FacebookSdk.executor = executor;
        }
    }
    return FacebookSdk.executor;
}

From source file:org.openmrs.module.openconceptlab.updater.Updater.java

private ThreadPoolExecutor newRunner() {
    return new ThreadPoolExecutor(0, THREAD_POOL_SIZE, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(THREAD_POOL_SIZE / 2), new RejectedExecutionHandler() {

                @Override/*from ww  w .  j  a v a2 s .c  o m*/
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    try {
                        executor.getQueue().put(r);
                    } catch (InterruptedException e) {
                        throw new RejectedExecutionException("Work discarded", e);
                    }
                }
            });
}

From source file:io.cloudslang.worker.management.services.WorkerManager.java

public void doRecovery() {

    //        Attempts to stop all actively executing tasks, halts the
    //        processing of waiting tasks, and returns a list of the tasks
    //        that were awaiting execution.
    ///*  w w w.ja  v a  2  s  .c o  m*/
    //        This method does not wait for actively executing tasks to
    //        terminate.
    //
    //        There are no guarantees beyond best-effort attempts to stop
    //        processing actively executing tasks.  For example, typical
    //        implementations will cancel via {@link Thread#interrupt}, so any
    //        task that fails to respond to interrupts may never terminate.
    try {
        synchronized (this) {
            executorService.shutdownNow(); //shutting down current running threads
            threadPoolVersion++; //updating the thread pool version to a new one - so current running threads will exit
            logger.warn(
                    "Worker is in doRecovery(). Cleaning state and cancelling running tasks. It may take up to 30 seconds...");
        }

        boolean finished = executorService.awaitTermination(30, TimeUnit.SECONDS);

        if (finished) {
            logger.warn("Worker succeeded to cancel running tasks during doRecovery().");
        } else {
            logger.warn("Not all running tasks responded to cancel.");
        }
    } catch (InterruptedException ex) {
        /*ignore*/}

    mapOfRunningTasks.clear();

    //Make new executor
    executorService = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, Long.MAX_VALUE,
            TimeUnit.NANOSECONDS, inBuffer,
            new WorkerThreadFactory((threadPoolVersion) + "_WorkerExecutionThread"));
}

From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinator.java

/**
 * Returns executor service that should be used for lease renewal.
 * @param maximumPoolSize Maximum allowed thread pool size
 * @return Executor service that should be used for lease renewal.
 *///from ww  w .  jav a 2s  . com
private static ExecutorService getLeaseRenewalExecutorService(int maximumPoolSize) {
    ThreadPoolExecutor exec = new ThreadPoolExecutor(maximumPoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), LEASE_RENEWAL_THREAD_FACTORY);
    exec.allowCoreThreadTimeOut(true);
    return exec;
}

From source file:com.brsanthu.googleanalytics.GoogleAnalytics.java

protected synchronized ThreadPoolExecutor createExecutor(GoogleAnalyticsConfig config) {
    return new ThreadPoolExecutor(0, config.getMaxThreads(), 5, TimeUnit.MINUTES,
            new LinkedBlockingDeque<Runnable>(), createThreadFactory());
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.TNTInputStream.java

/**
 * Creates default thread pool executor service for a given number of threads. Using this executor service tasks
 * queue size is unbound. Thus memory use may be high to store all producer thread created tasks.
 *
 * @param threadsQty/* w w w.j ava  2s .co m*/
 *            the number of threads in the pool
 *
 * @return the newly created thread pool executor
 *
 * @see ThreadPoolExecutor#ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue, ThreadFactory)
 */
private ExecutorService getDefaultExecutorService(int threadsQty) {
    StreamsThreadFactory stf = new StreamsThreadFactory("StreamDefaultExecutorThread-"); // NON-NLS
    stf.addThreadFactoryListener(new StreamsThreadFactoryListener());

    ThreadPoolExecutor tpe = new ThreadPoolExecutor(threadsQty, threadsQty, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(), stf);

    return tpe;
}

From source file:org.apache.hadoop.mapreduce.v2.app.launcher.ContainerLauncherImpl.java

protected void serviceStart() throws Exception {

    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("ContainerLauncher #%d").setDaemon(true)
            .build();//from   w ww.  ja v a  2  s  . c o m

    // Start with a default core-pool size of 10 and change it dynamically.
    launcherPool = new ThreadPoolExecutor(initialPoolSize, Integer.MAX_VALUE, 1, TimeUnit.HOURS,
            new LinkedBlockingQueue<Runnable>(), tf);
    eventHandlingThread = new Thread() {
        @Override
        public void run() {
            ContainerLauncherEvent event = null;
            Set<String> allNodes = new HashSet<String>();

            while (!stopped.get() && !Thread.currentThread().isInterrupted()) {
                try {
                    event = eventQueue.take();
                } catch (InterruptedException e) {
                    if (!stopped.get()) {
                        LOG.error("Returning, interrupted : " + e);
                    }
                    return;
                }
                allNodes.add(event.getContainerMgrAddress());

                int poolSize = launcherPool.getCorePoolSize();

                // See if we need up the pool size only if haven't reached the
                // maximum limit yet.
                if (poolSize != limitOnPoolSize) {

                    // nodes where containers will run at *this* point of time. This is
                    // *not* the cluster size and doesn't need to be.
                    int numNodes = allNodes.size();
                    int idealPoolSize = Math.min(limitOnPoolSize, numNodes);

                    if (poolSize < idealPoolSize) {
                        // Bump up the pool size to idealPoolSize+initialPoolSize, the
                        // later is just a buffer so we are not always increasing the
                        // pool-size
                        int newPoolSize = Math.min(limitOnPoolSize, idealPoolSize + initialPoolSize);
                        LOG.info("Setting ContainerLauncher pool size to " + newPoolSize
                                + " as number-of-nodes to talk to is " + numNodes);
                        launcherPool.setCorePoolSize(newPoolSize);
                    }
                }

                // the events from the queue are handled in parallel
                // using a thread pool
                launcherPool.execute(createEventProcessor(event));

                // TODO: Group launching of multiple containers to a single
                // NodeManager into a single connection
            }
        }
    };
    eventHandlingThread.setName("ContainerLauncher Event Handler");
    eventHandlingThread.start();
    super.serviceStart();
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProviderService.java

private ExecutorService createExecutor() {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 5, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private final AtomicInteger counter = new AtomicInteger();
                private final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
                    @Override/*from   w  ww  .ja  va2 s  .  c om*/
                    public void uncaughtException(Thread t, Throwable e) {
                        log.warn("Error occurred in asynchronous processing ", e);
                    }
                };

                @Override
                public Thread newThread(@Nonnull Runnable r) {
                    Thread thread = new Thread(r, createName());
                    thread.setDaemon(true);
                    thread.setPriority(Thread.MIN_PRIORITY);
                    thread.setUncaughtExceptionHandler(handler);
                    return thread;
                }

                private String createName() {
                    return "oak-lucene-" + counter.getAndIncrement();
                }
            });
    executor.setKeepAliveTime(1, TimeUnit.MINUTES);
    executor.allowCoreThreadTimeOut(true);
    return executor;
}