Last active
July 22, 2016 10:53
-
-
Save sadegh/bba0071ebdc6f5a8a4a956e859f5f86d to your computer and use it in GitHub Desktop.
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
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