Skip to content

Instantly share code, notes, and snippets.

@sadegh
Last active July 22, 2016 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sadegh/bba0071ebdc6f5a8a4a956e859f5f86d to your computer and use it in GitHub Desktop.
Save sadegh/bba0071ebdc6f5a8a4a956e859f5f86d to your computer and use it in GitHub Desktop.
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PausableExecutor extends ThreadPoolExecutor {
private boolean isPaused;
private ReentrantLock pauseLock = new ReentrantLock();
private Condition unPaused = pauseLock.newCondition();
/**
* Default constructor for a simple fixed threadpool
*/
public PausableExecutor(int corePoolSize) {
super("PausebaleExecutor", corePoolSize, corePoolSize, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
/**
* Executed before a task is assigned to a thread.
*/
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
pauseLock.lock();
try {
while (isPaused) unPaused.await();
} catch (InterruptedException ie) {
t.interrupt();
} finally {
pauseLock.unlock();
}
}
/**
* Pause the threadpool. Running tasks will continue running, but new tasks
* will not start until the threadpool is resumed.
*/
public void pause() {
pauseLock.lock();
try {
isPaused = true;
} finally {
pauseLock.unlock();
}
}
/**
* Resume the threadpool.
*/
public void resume() {
pauseLock.lock();
try {
isPaused = false;
unPaused.signalAll();
} finally {
pauseLock.unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment