[concurrency-interest] the remove-on-cancel policy on ScheduledThreadPoolExecutor

"이희승 (Trustin Lee)" trustin at gmail.com
Tue Aug 31 05:18:50 EDT 2010


ScheduledThreadPoolExecutor's queue implementation is heap, and it means
removing an arbitrary task from the queue takes O(logN) time which is
not very optimal.  If removal takes place very often, you will observe
very high CPU usage.

If remove-on-cancel policy became available, someone might have
addressed this issue in JDK 7.  However, I did not read the code yet, so
someone else will step up and let us know.

Anyway, you can call ThreadPoolExecutor.purge() to remove the cancelled
tasks from the queue manually.  Calling it for every 1000th cancellation
for example helped me a lot.

Alternatively, you can try a different timer implementation that has
minimal cancellation cost.  I find hashed wheel timer very useful:

    http://www.cse.wustl.edu/~cdgill/courses/cs6874/TimingWheels.ppt

and the following is my implementation for Netty:


http://docs.jboss.org/netty/3.2/xref/org/jboss/netty/util/HashedWheelTimer.html

HTH,
Trustin

On 08/31/2010 02:12 PM, Sangjin Lee wrote:
> Maybe this has been discussed in the past...
> 
> I've always been curious why ScheduledFuture.cancel() would not also
> remove tasks from the queue (so would keep them live until the delay
> elapses) as an optional behavior. I know one can override the
> decorateTask() method to achieve the same effect, but it's slightly less
> than optimal as you need to create an additional delegate object to
> achieve the same goal. Then I checked the upcoming JDK 7 changes, and
> there seems to be such a setting called the remove-on-cancel policy!
> 
> I looked some old versions of ScheduledThreadPoolExecutor, and it seems
> this behavior was in but was removed at some point? Could someone shed
> light on why it was decided not to include it in the existing versions
> of JDK? And why the change in JDK 7? I would love to have this behavior,
> but I'm just curious about the reason behind these decisions. Thanks!
> 
> Regards,
> Sangjin
> 
> 
> 
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

-- 
what we call human nature in actuality is human habit
http://gleamynode.net/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 293 bytes
Desc: OpenPGP digital signature
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20100831/412efa97/attachment.bin>


More information about the Concurrency-interest mailing list