[concurrency-interest] Strange behaviour with LinkedBlockingQueue JDK 1.4 backport

Jean Morissette jean.morissette666@videotron.ca
Mon, 13 Dec 2004 11:30:26 -0500


Hi,
Running this test on 
edu.emory.mathcs.backport.java.util.concurrent.LinkedBlockingQueue cause 
the Producer and Consumer threads to block indefinitely.  Am I missing 
something?

public class QueueTest {

   private static final int CAPACITY = 10;
   static LinkedBlockingQueue q = new LinkedBlockingQueue(CAPACITY);

   static class Producer implements Runnable {
     public void run() {
       while (true) {
         try {
           q.put(new Object());
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
     }
   }

   static class Consumer implements Runnable {
     int i;
     public void run() {
       List list = new ArrayList();
       int size = 0;
       long t1 = System.currentTimeMillis();
       while (true) {
         try {
           q.drainTo(list);
           size = list.size();
           i += size;
           list.clear();
           if (i >= 5) break;
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
       long t2 = System.currentTimeMillis();
       System.out.println("time = " + (t2 -t1));
     }
   }

   public static void main(String[] args) throws InterruptedException {
     new Thread(new Consumer()).start();;
     new Thread(new Producer()).start();;

     while (true) {
       Thread.sleep(10000000);
     }
   }

}