Executor interface in java.util.concurrent package lets you submit Runnable tasks. Executor then handles the execution of the task. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.
Contract of Executor interface has a single method: execute(Runnable command)
This Executor implementation uses a Lock to pause/resume the execution.
public class PausableExecutor extends ThreadPoolExecutor {
private boolean isPaused = false;
private Lock pauseLock = new ReentrantLock();
private Condition unpaused = pauseLock.newCondition();
public PausableExecutor() {
super(5, 5, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
pauseLock.lock();
try {
while (isPaused) {
unpaused.await();
}
} catch (InterruptedException e) {
t.interrupt();
} finally {
pauseLock.unlock();
}
}
public void pause() {
pauseLock.lock();
try {
isPaused = true;
} finally {
pauseLock.unlock();
}
}
public void resume() {
pauseLock.lock();
try {
isPaused = false;
unpaused.signal();
} finally {
pauseLock.unlock();
}
}
}