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:com.dumontierlab.pdb2rdf.Pdb2Rdf.java

private static ExecutorService getThreadPool(CommandLine cmd) {
    // twice the number of PU
    final Object monitor = new Object();
    int numberOfThreads = getNumberOfThreads(cmd);
    LOG.info("Using " + numberOfThreads + " threads.");
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, 10,
            TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(1), new RejectedExecutionHandler() {
                @Override/*from   w ww. j av  a  2  s  .com*/
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    synchronized (monitor) {
                        try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    executor.execute(r);
                }
            }) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            synchronized (monitor) {
                monitor.notify();
            }
            super.afterExecute(r, t);
        }
    };

    return threadPool;
}

From source file:com.sentaroh.android.TaskAutomation.TaskManager.java

static final public void buildTaskCtrlThreadPool(final EnvironmentParms envParms,
        final TaskManagerParms taskMgrParms, final CommonUtilities util) {
    if (taskMgrParms.taskControlThreadPool != null)
        removeTaskCtrlThreadPool(envParms, taskMgrParms, util);
    SynchronousQueue<Runnable> slq = new SynchronousQueue<Runnable>();
    RejectedExecutionHandler rh = new RejectedExecutionHandler() {
        @Override/* w w  w . j  a va  2s  . c o  m*/
        public void rejectedExecution(final Runnable r, ThreadPoolExecutor executor) {
            util.addDebugMsg(1, "W", "Task control reject handler entered.");
            envParms.statsUseOutsideThreadPoolCountTaskCtrl++;
            Thread th = new Thread() {
                @Override
                public void run() {
                    r.run();
                }
            };
            th.start();
        }
    };
    taskMgrParms.taskControlThreadPool = new ThreadPoolExecutor(TASK_CTRL_THREAD_POOL_COUNT,
            TASK_CTRL_THREAD_POOL_COUNT, 10, TimeUnit.SECONDS, slq, rh);
    for (int i = 0; i < TASK_CTRL_THREAD_POOL_COUNT; i++) {
        final int num = i + 1;
        Runnable rt = new Runnable() {
            @Override
            public void run() {
                Thread.currentThread().setPriority(THREAD_PRIORITY_TASK_CTRL);
                Thread.currentThread().setName("TaskCtrl-" + num);
            }
        };
        taskMgrParms.taskControlThreadPool.execute(rt);
    }
    taskMgrParms.taskControlThreadPool.prestartAllCoreThreads();
    util.addDebugMsg(1, "I", "Task control thread pool was created.");
}

From source file:org.haiku.haikudepotserver.job.LocalJobServiceImpl.java

@Override
public void doStart() {
    try {/*  ww  w.  java2s .c  o  m*/
        Preconditions.checkState(null == executor);

        LOGGER.info("will start service");

        jobs = Maps.newHashMap();

        executor = new ThreadPoolExecutor(0, // core pool size
                1, // max pool size
                1L, // time to shutdown threads
                TimeUnit.MINUTES, runnables, new ThreadPoolExecutor.AbortPolicy());

        notifyStarted();

        LOGGER.info("did start service");
    } catch (Throwable th) {
        notifyFailed(th);
    }
}

From source file:org.apache.hadoop.mapreduce.v2.hs.HistoryFileManager.java

protected ThreadPoolExecutor createMoveToDoneThreadPool(int numMoveThreads) {
    ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("MoveIntermediateToDone Thread #%d").build();
    return new ThreadPoolExecutor(numMoveThreads, numMoveThreads, 1, TimeUnit.HOURS,
            new LinkedBlockingQueue<Runnable>(), tf);
}

From source file:SwingWorker.java

/**
 * returns workersExecutorService./* w w  w. ja  v  a 2  s .c om*/
 *
 * returns the service stored in the appContext or creates it if
 * necessary. If the last one it triggers autoShutdown thread to
 * get started.
 * 
 * @return ExecutorService for the {@code SwingWorkers}
 * @see #startAutoShutdownThread
 */
private static synchronized ExecutorService getWorkersExecutorService() {
    if (executorService == null) {
        //this creates non-daemon threads. 
        ThreadFactory threadFactory = new ThreadFactory() {
            final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

            public Thread newThread(final Runnable r) {
                Thread thread = defaultFactory.newThread(r);
                thread.setName("SwingWorker-" + thread.getName());
                return thread;
            }
        };

        /*
         * We want a to have no more than MAX_WORKER_THREADS
         * running threads.
         *
         * We want a worker thread to wait no longer than 1 second
         * for new tasks before terminating.
         */
        executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS, 1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), threadFactory) {

            private final ReentrantLock pauseLock = new ReentrantLock();
            private final Condition unpaused = pauseLock.newCondition();
            private boolean isPaused = false;
            private final ReentrantLock executeLock = new ReentrantLock();

            @Override
            public void execute(Runnable command) {
                /*
                 * ThreadPoolExecutor first tries to run task
                 * in a corePool. If all threads are busy it
                 * tries to add task to the waiting queue. If it
                 * fails it run task in maximumPool.
                 *
                 * We want corePool to be 0 and
                 * maximumPool to be MAX_WORKER_THREADS
                 * We need to change the order of the execution.
                 * First try corePool then try maximumPool
                 * pool and only then store to the waiting
                 * queue. We can not do that because we would
                 * need access to the private methods.
                 *
                 * Instead we enlarge corePool to
                 * MAX_WORKER_THREADS before the execution and
                 * shrink it back to 0 after. 
                 * It does pretty much what we need.
                 *
                 * While we changing the corePoolSize we need
                 * to stop running worker threads from accepting new
                 * tasks.
                 */

                //we need atomicity for the execute method.
                executeLock.lock();
                try {

                    pauseLock.lock();
                    try {
                        isPaused = true;
                    } finally {
                        pauseLock.unlock();
                    }

                    setCorePoolSize(MAX_WORKER_THREADS);
                    super.execute(command);
                    setCorePoolSize(0);

                    pauseLock.lock();
                    try {
                        isPaused = false;
                        unpaused.signalAll();
                    } finally {
                        pauseLock.unlock();
                    }
                } finally {
                    executeLock.unlock();
                }
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                pauseLock.lock();
                try {
                    while (isPaused) {
                        unpaused.await();
                    }
                } catch (InterruptedException ignore) {

                } finally {
                    pauseLock.unlock();
                }
            }
        };
    }
    return executorService;
}

From source file:org.jvnet.hudson.test.JenkinsRule.java

/**
 * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation
 * that we need for testing./*from w w w .ja v  a 2s. c o  m*/
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server();

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[] { new WebXmlConfiguration(), new NoListenerConfiguration() });
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);

    SocketConnector connector = new SocketConnector();
    connector.setHeaderBufferSize(12 * 1024); // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    if (System.getProperty("port") != null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.setThreadPool(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("Jetty Thread Pool");
                    return t;
                }
            })));
    server.addConnector(connector);
    server.addUserRealm(configureUserRealm());
    server.start();

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}

From source file:org.openconcerto.sql.model.SQLDataSource.java

private synchronized final ExecutorService getExec() {
    if (this.exec == null) {
        // not daemon since we want the connections to be returned
        final ThreadFactory factory = new ThreadFactory(
                SQLDataSource.class.getSimpleName() + " " + this.toString() + " exec n ", false);
        // a rather larger number of threads since all they do is wait severals seconds
        this.exec = new ThreadPoolExecutor(0, 32, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
                factory);/*  ww  w .  j a v  a2  s  . co m*/
    }
    return this.exec;
}

From source file:org.jdesktop.swingworker.AccumulativeRunnable.java

/**
 * returns workersExecutorService.//from w  w w  .j a v a 2s . c  o  m
 *
 * returns the service stored in the appContext or creates it if
 * necessary. If the last one it triggers autoShutdown thread to
 * get started.
 * 
 * @return ExecutorService for the {@code SwingWorkers}
 * @see #startAutoShutdownThread
 */
private static synchronized ExecutorService getWorkersExecutorService() {
    if (executorService == null) {
        //this creates non-daemon threads. 
        ThreadFactory threadFactory = 
            new ThreadFactory() {
                final AtomicInteger threadNumber = new AtomicInteger(1);
                public Thread newThread(final Runnable r) {
                    StringBuilder name = 
                        new StringBuilder("SwingWorker-pool-");
                    name.append(System.identityHashCode(this));
                    name.append("-thread-");
                    name.append(threadNumber.getAndIncrement());
                             
                    Thread t = new Thread(r, name.toString());;
                    if (t.isDaemon())
                        t.setDaemon(false);
                    if (t.getPriority() != Thread.NORM_PRIORITY)
                        t.setPriority(Thread.NORM_PRIORITY);
                    return t;
                }
            };

        /*
         * We want a to have no more than MAX_WORKER_THREADS
         * running threads.
         *
         * We want a worker thread to wait no longer than 1 second
         * for new tasks before terminating.
         */
        executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS,
                                     5L, TimeUnit.SECONDS,
                                     new LinkedBlockingQueue<Runnable>(),
                                     threadFactory) {

                private final ReentrantLock pauseLock = new ReentrantLock();
                private final Condition unpaused = pauseLock.newCondition();
                private boolean isPaused = false;
                private final ReentrantLock executeLock = new ReentrantLock();
                    
                @Override
                public void execute(Runnable command) {
                    /*
                     * ThreadPoolExecutor first tries to run task
                     * in a corePool. If all threads are busy it
                     * tries to add task to the waiting queue. If it
                     * fails it run task in maximumPool.
                     *
                     * We want corePool to be 0 and
                     * maximumPool to be MAX_WORKER_THREADS
                     * We need to change the order of the execution.
                     * First try corePool then try maximumPool
                     * pool and only then store to the waiting
                     * queue. We can not do that because we would
                     * need access to the private methods.
                     *
                     * Instead we enlarge corePool to
                     * MAX_WORKER_THREADS before the execution and
                     * shrink it back to 0 after. 
                     * It does pretty much what we need.
                     *
                     * While we changing the corePoolSize we need
                     * to stop running worker threads from accepting new
                     * tasks.
                     */
                        
                    //we need atomicity for the execute method.
                    executeLock.lock();
                    try {

                        pauseLock.lock();
                        try {
                            isPaused = true;
                        } finally {
                            pauseLock.unlock();
                        }
                            
                        setCorePoolSize(MAX_WORKER_THREADS);
                        super.execute(command);
                        setCorePoolSize(0);
                            
                        pauseLock.lock();
                        try {
                            isPaused = false;
                            unpaused.signalAll();
                        } finally {
                            pauseLock.unlock();
                        }
                    } finally {
                        executeLock.unlock();
                    }
                }
                @Override 
                protected void afterExecute(Runnable r, Throwable t) { 
                    super.afterExecute(r, t);
                    pauseLock.lock();
                    try {
                        while(isPaused) {
                            unpaused.await();
                        }
                    } catch(InterruptedException ignore) {
                            
                    } finally {
                        pauseLock.unlock();
                    }
                }
            };
    }
    return executorService; 
}