[concurrency-interest] Is there a ConcurrentBlockingQueue ??

Hanson Char hanson.char at gmail.com
Mon Mar 26 16:32:41 EDT 2007


However, it does seem the algorithm can be further improved to
1) reduce the number of "unparked" called on a waiting threads;
2) ensure max of only 1 marker is created for a waiting thread; and
3) maintain the fairness at the same time.

Like so:

   public E take() throws InterruptedException
   {
       ThreadMarker m = null;

       for (;;) {
           E e = q.poll();

           if (e != null)
               return e;
           if (m == null)
           {   // thread has never been marked
               m = new ThreadMarker(Thread.currentThread());

               if (Thread.interrupted())
               {   // avoid the parkq.offer(m) if already interrupted
                   throw new InterruptedException();
               }
               parkq.offer(m);
               // check again in case there is data race
               e = q.poll();

               if (e != null)
               {   // data race indeed
                   m.parked = false;
                   return e;
               }
           }
           LockSupport.park();

           if (Thread.interrupted())
           {
               m.parked = false;
               throw new InterruptedException();
           }
       }
   }

Hanson Char


More information about the Concurrency-interest mailing list