[concurrency-interest] overview new features -> tim.

Tim Peierls tim at peierls.net
Tue Sep 6 02:11:40 EDT 2005


> Peter Veentjer - Anchor Men wrote:
>> I don`t think that is a very good solution because the exchange of 
>> messages is combined with storage of messages.
> 
Doug Lea wrote:
> That was my original rationale for dl.uti.concurrent versions. But the
> rest of the world (including, now, me) disagrees. Support for standard
> Collection methods was probably the most frequently requested feature.
> Integration into Collections makes these classes more widely usable. And
> (sorry to say) the only people inconvenienced by it can cope
> with this a lot more easily than if it were the other way around.

And if you're having trouble coping, just do this:

   public interface Puttable<E> {
       boolean offer(E o);
       boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException;
       void put(E o) throws InterruptedException;
   }

   public interface Takeable<E> {
       E poll();
       E pool(long timeout, TimeUnit unit) throws InterruptedException;
       E take() throws InterruptedException;
   }

   public class PTAdapters {
       public static <E> Puttable<E> asPuttable(BlockingQueue<E> q) {
           return new Puttable<E>() {
               public boolean offer(E o) { return q.offer(o); }
               public boolean offer(E o, long timeout, TimeUnit unit)
                   throws InterruptedException { return q.offer(o, timeout, unit); }
               public void put(E o) throws InterruptedException { q.put(o); }
           };
       }
       public static <E> Takeable<E> asTakeable(BlockingQueue<E> q) {
           return new Takeable<E>() {
               public E poll() { return q.poll(); }
               public E poll(long timeout, TimeUnit unit)
                   throws InterruptedException { return q.poll(timeout, unit); }
               public E take() throws InterruptedException { return q.take(); }
           };
       }
       private PTAdapters() {} // uninstantiable
   }

   // sample use
   class Producer {
       Producer(Puttable<Long> p) {...}
       ...
   }
   class Consumer {
       Consumer(Takeable<Long> t) {...}
       ...
   }
   BlockingQueue<Long> queue = new ArrayBlockingQueue<Long>(10);
   Executor exec = newFixedThreadPool(2);
   exec.execute(new Producer(asPuttable(queue)));
   exec.execute(new Consumer(asTakeable(queue)));
   exec.shutdown();

There, now you have them back. :-)

--tim



More information about the Concurrency-interest mailing list