[concurrency-interest] Whats up with the ThreadPoolExecutor?

Tim Peierls tim at peierls.net
Mon Aug 22 16:29:02 EDT 2005


Ravinder Singh wrote:
> I don't know if this is a bug or me just using it wrongly. But I add 
> work to the pool, and I add the same Runnable each time. Since I try to 
> avoid GC. But it seems that it doesn't process the full queue. If I 
> create a new Runnable each time its ok.

There may be a bug in java.util.concurrent.ThreadPoolExecutor (and thus in the
backport TPE).

     public void execute(Runnable command) {
         for (;;) {
             ...
             if (workQueue.offer(command))
                 return;
             Runnable r = addIfUnderMaximumPoolSize(command);
             if (r == command)  // !!!
                 return;
             if (r == null) { /* reject */ }
             // else retry
         }
     }

On the line marked "!!!", there is an identity comparison. When you use the 
same Runnable object, this test can succeed even though the command hasn't run.

However, it's not clear to me that TPE should have to support this kind of 
thing. The workaround is simple: use separate Runnable instances.


>   static private int cSt, cWrk;
> 
>   public static class Woerker implements Runnable
>   {
>       public void run()
>       {
>           cSt++;
>       }
>   }

This is not the main problem, but you are incrementing the cSt counter without 
any kind of synchronization, so the cSt value you are seeing is suspect.

--tim



More information about the Concurrency-interest mailing list