Re: ThreadPoolExecutor backport
Lew a =E9crit :
Philipp wrote:
class PausableThreadPoolExecutor extends ThreadPoolExecutor {
private boolean isPaused;
private ReentrantLock pauseLock = new ReentrantLock();
private Condition unpaused = pauseLock.newCondition();
public PausableThreadPoolExecutor(...) { super(...);
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();
}
}
public void pause() {
pauseLock.lock();
try {
isPaused = true;
} finally {
pauseLock.unlock();
}
}
public void resume() {
pauseLock.lock();
try {
isPaused = false;
unpaused.signalAll();
} finally {
pauseLock.unlock();
}
}
}}
Q: Why does the boolean flag isPaused need not be volatile?
As I see it, it will be polled and set by different threads and
nothing guarantees a memory barrier.
Nothing but the 'pauseLock.lock()', that is.
Thanks for your non-answer. It made me look harder.
Actually, the thing that happens is that in beforeExecute(),
unpaused.await() unlocks the acquired lock pauseLock. This then
(later) gets locked by resume() where signalAll awakes the waiting
thread in beforeExecute(). At this time, the waiting thread is awake,
but cannot execute because it must first reacquire the lock (which is
still held in resume() ). As soon as resume() releases the lock, it is
reacquired by beforeExecute(). Now what makes it all work without the
volatile keyword, is that the unlock() in resume() establishes a
happens-before relation with respect to a subsequent lock of
pauseLock. So the value of isPaused is updated as soon as the waiting
thread starts to run again.
Phil