Reorder Queue in Java ThreadPoolExecutor

Possible duplicate:
Java artists: how to prioritize a task?

I have a ThreadPoolExecutor built using LinkedBlockingDequeue and I want to manipulate the base queue, however, reading this in the documentation, I'm very nervous.

Queue Service

The getQueue () method allows access to the work queue for monitoring and debugging purposes. Using this method for any other purpose is strongly discouraged. The two methods provided, remove (java.lang.Runnable) and purge () are available to help in the reclamation of the repository when a large number of tasks are canceled.

In particular, I want to be able to

  • Check the queue to see if the item exists. I assume this is normal, since no lock is required to just view items in the queue.
  • I want to reorder the queue based on some signal. This can obviously be unpleasant. I was wondering if there is a preferred way to do this so that I don't mess up the queue for other purposes.

thanks

+8
java multithreading
source share
1 answer

getQueue() will always return the exact BlockingQueue<Runnable> that you pass to ThreadPoolExecutor .

The concern with the documentation is that you can easily run into double-launch problems if you cannot guarantee the safety of the BlockingQueue stream. If you use PriorityBlockingQueue and use only remove and add (or, more directly, offer ), then you will be safe, and you can even do it directly from getQueue() .

In other words, whenever your signal tells you that the Runnable priority has been changed, you must remove it and check the result of the deletion ( true if it was deleted), and only if it was deleted, you must re-add it. You do not guarantee that something will not be achieved between these operations, but you will at least be guaranteed that you will not run Runnable twice, which can be easily done if you do this using containsremoveadd .

Either that, or you can write your own implementation of BlockingQueue that uses a Comparator (e.g. PriorityBlockingQueue ) that finds the highest priority when new information is requested. It sounds a lot more considering the various interfaces.

+4
source share

All Articles