[concurrency-interest] takeOrWake() method for a LinkedBlockingQueue

Jeff Hain jeffhain at rocketmail.com
Sun Nov 7 07:47:56 EST 2010


Hello.

I'm currently optimizing some scheduler (or Executor) implementation:
for ASAP schedules, it was using a LinkedList with synchronization, then
I switched to a LinkedBlockingQueue, using add(E) and take() methods.

The scheduler has start()/stop() methods, so I need to be able to tell worker
threads in take() method to stop waiting for an ASAP schedule, and wait for
being allowed to work again.
(pending schedules need to be reachable any time, for there is a 
cancelSchedules()
method, so if take() returns a schedule and work status is false, I can't just 
wait for
it to be true again, since after take() returns the schedule is no longer 
reachable)

The simplest way I found to have a take() that can stop waiting was to extend
LinkedBlockingQueue, and add a takeOrWake() method, which is basically
take() with
>while (count.get() == 0) {
>   notEmpty.await();
>}
replaced with
>if (count.get() == 0) {
>   notEmpty.await();
>   if (count.get() == 0) {
>      // signal or spurious wake-up
>      return null;
>   }
>}
(I also removed the call to signalNotFull(), which breaks put(E) and
offer(E,long,TimeUnit) methods, but I don't use them.)

I had to use reflection to access some private fields and dequeue()
method used in take() method.

My concern is, I don't really like this solution, for reflection is a bit
hacky and might have some performance hit.

On the other hand, I don't really want to copy-paste-modify the whole
LinkedBlockingQueue class, and calling dequeue() through reflection
does not seem to have a noticeable performance hit in my benches.

If anyone has a nicer solution to this problem, or can confirm that
reflection should not hurt in that case, I would be pleased to hear it.

Regards,

Jeff


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20101107/943ad0da/attachment.html>


More information about the Concurrency-interest mailing list