Skip to content

Instantly share code, notes, and snippets.

@JBirdVegas
Created November 15, 2016 22:01
Show Gist options
  • Select an option

  • Save JBirdVegas/07e979ea84cadc08eced6e95b7b309e0 to your computer and use it in GitHub Desktop.

Select an option

Save JBirdVegas/07e979ea84cadc08eced6e95b7b309e0 to your computer and use it in GitHub Desktop.
Example thread pool manager in java
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