Created
November 15, 2016 22:01
-
-
Save JBirdVegas/07e979ea84cadc08eced6e95b7b309e0 to your computer and use it in GitHub Desktop.
Example thread pool manager in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.jbirdvegas.testing; | |
| import java.util.List; | |
| import java.util.concurrent.ArrayBlockingQueue; | |
| import java.util.concurrent.ThreadPoolExecutor; | |
| import java.util.concurrent.TimeUnit; | |
| public class ThreadPoolWorkHandler { | |
| private static final int QUEUE_SIZE = 50; | |
| private static final int NUMBER_OF_THREADS_WHEN_IDLE = 3; | |
| private static final int MAX_THREADS_IN_POOL = 8; | |
| private static final long IDLE_THREAD_LIVES_AFTER_WHEN_NO_WORK = 30; | |
| private static ThreadPoolWorkHandler sInstance; | |
| private final ArrayBlockingQueue<Runnable> mQueue; | |
| private final ThreadPoolExecutor mThreadPool; | |
| private ThreadPoolWorkHandler() { | |
| mQueue = new ArrayBlockingQueue<>(QUEUE_SIZE); | |
| mThreadPool = new ThreadPoolExecutor(NUMBER_OF_THREADS_WHEN_IDLE, | |
| MAX_THREADS_IN_POOL, | |
| IDLE_THREAD_LIVES_AFTER_WHEN_NO_WORK, | |
| TimeUnit.SECONDS, | |
| mQueue); | |
| } | |
| public static ThreadPoolWorkHandler getInstance() { | |
| if (sInstance == null) { | |
| sInstance = new ThreadPoolWorkHandler(); | |
| } | |
| return sInstance; | |
| } | |
| public void submitWork(Runnable work) { | |
| mQueue.add(work); | |
| } | |
| /** | |
| * Shuts down the threads when all submitted work is complete | |
| */ | |
| public void orderlyShutdown() { | |
| mThreadPool.shutdown(); | |
| } | |
| /** | |
| * Does not wait for all submitted work to be complete before shutting down | |
| * | |
| * @return work that was awaiting processing | |
| */ | |
| public List<Runnable> shutdownNow() { | |
| return mThreadPool.shutdownNow(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment