[concurrency-interest] ScheduledThreadPoolExecutor woes

Bela Ban belaban at yahoo.com
Thu Jan 18 10:12:09 EST 2007


I'm trying to use ScheduledThreadPoolExecutor (as suggested by Brian in 
his book) as a replacement for java.util.Timer.

Turns out this class is more or less sealed (cannot be extended because 
almost all interesting methods are final or private). I assume that this 
was done by intention, if so what was the rationale ? That stupid users 
like me don't mess around with it ? :-)

I want to implement 2 things extending ScheduledThreadPoolExecutor:

#1 No thread should be running when no tasks are in the queue. I did 
this using the following kludge in my subclass:

|public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long 
initialDelay, long delay, TimeUnit unit) {
     startCoreThread();
     return super.scheduleWithFixedDelay(command, initialDelay, delay, 
unit);
 }

private void startCoreThread() {
   if(getPoolSize() <= 0) {
       setCorePoolSize(1);
       prestartCoreThread();
       setCorePoolSize(0);
   }
}|

Not very nice, plus not thread safe, but here I don't care if I 
accidentally start more than 1 core thread (I might protect this with a 
lock).


#2 I want to run tasks with flexible (=computed) versus fixed intervals

For example, for message retransmission a la TCP, I'd like to use 
exponential backoff, so my intervals would increase *every time the task 
is executed*.  In another case, I use a random interval with a min/max 
time range.
I was thinking of subclassing ScheduledFutureTask.runPeriodic() and - 
before resubmitting the task - compute the new interval, but this method 
is private too arghh !

Do I have to write my own timer then (e.g. off of AbstractExecutorService)?
Cheers,

-- 
Bela Ban
Lead JGroups / JBoss Clustering team
JBoss - a division of Red Hat



More information about the Concurrency-interest mailing list