[concurrency-interest] ThreadPoolExecutor customization proposal/question

hernan.otero at jpmchase.com hernan.otero at jpmchase.com
Fri Apr 1 17:55:47 EST 2005


I would like to use a ThreadPoolExecutor but would like to impose a couple
of restrictions on how tasks (Runnables) are executed.  Basically, I would
like to have each task execute on a specific "context" (each context having
a unique String-typed id).  I would like my executor to guarantee
serialization of the tasks at the context level (e.g. no two tasks for the
same context should ever be executed in parallel).  So if two tasks are
queued in order (e.g. by the same thread), then their execution should also
be guaranteed to execute in the same order.

If I were to implement this as a customization to the existing
ThreadPoolExecutor, I would probably think of going the following route:

interface RunnableContext
{

}

interface ContextRunnable extends Runnable
{

RunnableContext getContext();

}

public class ThreadPoolContextExecutor extends ThreadPoolExecutor {

Runnable getTask() {
  // the code that looks for the next task would need to skip tasks for
"currently busy" contexts
}

public void execute(Runnable task)
{
    // we want an exception if task is not a ContextRunnable
    ContextRunnable contextTask = (ContextRunnable) task;
    ...
}

protected void beforeExecute(Thread t, Runnable r) {
    ContextRunnable contextTask = (ContextRunnable) r;
    // assert that contextTask.getContext() context's not currently marked
as busy
    // somehow mark the fact that contextTask.getContext() is now busy
}

protected void afterExecute(Thread t, Runnable r) {
    ContextRunnable contextTask = (ContextRunnable) r;
    // assert that contextTask.getContext() context's currently marked as
busy
    // mark contextTask.getContext() as no longer busy
}

}

Would the above be the recommended way to implement such functionality?  Or
are there other hooks I missed which would make this easier to implement?

Also, I'm thinking this may not be a very rare need and was wondering if
there has been any thought given to something like this in the past.  It
might be worth considering it as a potential future enhancement to the
library.

Thanks in advance,

Hernan



More information about the Concurrency-interest mailing list