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

Martin Buchholz martinrb at google.com
Sun Nov 7 17:58:12 EST 2010

Writing a thread pool is non-trivial.

ThreadPoolExecutor tackles some of the same sort of issues, e.g. need
to notify waiting threads on shutdown.

The most obvious thing to do is to interrupt waiting threads, have
them catch InterruptedException, and then reexamine the state of the
executor.  See TPE.interruptIdleWorkers for inspiration.


On Sun, Nov 7, 2010 at 04:47, Jeff Hain <jeffhain at rocketmail.com> wrote:
> 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
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest

More information about the Concurrency-interest mailing list