Possible Duplicate:
Java Executors: how can I set task priority?
I have a ThreadPoolExecutor built using a LinkedBlockingDequeue and I want to manipulate the underlying queue, however reading this in the documentation makes me very nervous.
Queue maintenance
Method getQueue() allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged. Two supplied methods, remove(java.lang.Runnable) and purge() are available to assist in storage reclamation when large numbers of queued tasks become cancelled.
Specifically I want to be able to
Thanks
getQueue()
will always return the exact BlockingQueue<Runnable>
that you pass into the ThreadPoolExecutor
.
The worry with the documentation is that you could easily run into issues with double-running if you cannot guarantee the thread safety of the BlockingQueue
. If you use a PriorityBlockingQueue
, and only use remove
and add
(or, more directly, offer
), then you will be safe, and you can even do it directly from the getQueue()
.
In other words, whenever your signal tells you that some Runnable
's priority has changed, then you should remove
it and check the result of the remove (true
if removed), and only if it was actually removed, then you should re-add it. You are not guaranteed that something won't be picked up inbetween those operations, but you are at least guaranteed that you will not double-run the Runnable
, which could easily happen if done with contains
-> remove
-> add
.
Either that, or you can write your own implementation of a BlockingQueue
that uses a Comparator
(like the PriorityBlockingQueue
) that finds the highest priority whenever asked for new data. This sounds like a lot more work given the various interfaces involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With