[concurrency-interest] Pausing Executors

Doug Lea dl@cs.oswego.edu
Tue, 16 Sep 2003 07:56:05 -0400


Hi Peter,

I hope you don't mind me CC'ing the JSR166 concurrency-interest list
on reply.

Your question/suggestion about dl.u.c PooledExecutor...

>    This allowed me to pause() the thread queue to ensure nothing was
> happening.  The pause() is called by a gui request, which is not a thread
> inside the pool. This allows me to ensure all the tasks in the queue stop
> cleanly in a way that can be resumed.  This was used to pause a game before
> saving its state. 

Since there are several possible senses and policies for what you
might mean by "pausing" (for example, whether multiple, "stacked"
pause/resumes are allowed), and pausing doesn't always mix nicely with
other tunable settings/policies, it would probably be a mistake to
build this into the main thread pool class. But in the JSR166
ThreadPoolExecutor version, you can to do something like this using
before/after hooks in a subclass. Here's one way to set up the
simplest policy, using JSR166 lock/condition classes, just for the
sake of illustration (in this case you could probably more easily just
use builtin sync):

class PausableThreadPoolExecutor extends ThreadPoolExecutor {
  private boolean isPaused;
  private ReentrantLock pauseLock = new ReentrantLock();
  private Condition unpaused = pauseLock.newCondition();

  protected void beforeExecute(Thread t, Runnable r) {
    super.beforeExecute(t, r);
    pauseLock.lock();
    try {
      while (isPaused) unpaused.await();
    } catch(InterruptedException ie) {
      Thread.currentThread().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();
    }
  }
}

-- 
Doug Lea, Computer Science Department, SUNY Oswego, Oswego, NY 13126 USA
dl@cs.oswego.edu 315-312-2688 FAX:315-312-5424 http://gee.cs.oswego.edu/