1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  */
  22 
  23 /*
  24  * This file is available under and governed by the GNU General Public
  25  * License version 2 only, as published by the Free Software Foundation.
  26  * However, the following notice accompanied the original version of this
  27  * file:
  28  *
  29  * Written by Doug Lea with assistance from members of JCP JSR-166
  30  * Expert Group and released to the public domain, as explained at
  31  * http://creativecommons.org/publicdomain/zero/1.0/
  32  */
  33 
  34 /*
  35  * @test
  36  * @bug 4486658
  37  * @compile -source 1.5 MultipleProducersSingleConsumerLoops.java
  38  * @run main/timeout=3600 MultipleProducersSingleConsumerLoops
  39  * @summary  multiple producers and single consumer using blocking queues
  40  */
  41 
  42 import java.util.concurrent.*;
  43 
  44 public class MultipleProducersSingleConsumerLoops {
  45     static final int CAPACITY =      100;
  46     static final ExecutorService pool = Executors.newCachedThreadPool();
  47     static boolean print = false;
  48     static int producerSum;
  49     static int consumerSum;
  50 
  51     static synchronized void addProducerSum(int x) {
  52         producerSum += x;
  53     }
  54 
  55     static synchronized void addConsumerSum(int x) {
  56         consumerSum += x;
  57     }
  58 
  59     static synchronized void checkSum() {
  60         if (producerSum != consumerSum)
  61             throw new Error("CheckSum mismatch");
  62     }
  63 
  64     public static void main(String[] args) throws Exception {
  65         int maxProducers = 5;
  66         int iters = 100000;
  67 
  68         if (args.length > 0)
  69             maxProducers = Integer.parseInt(args[0]);
  70 
  71         print = false;
  72         System.out.println("Warmup...");
  73         oneTest(1, 10000);
  74         Thread.sleep(100);
  75         oneTest(2, 10000);
  76         Thread.sleep(100);
  77         print = true;
  78 
  79         for (int i = 1; i <= maxProducers; i += (i+1) >>> 1) {
  80             System.out.println("----------------------------------------");
  81             System.out.println("Producers:" + i);
  82             oneTest(i, iters);
  83             Thread.sleep(100);
  84         }
  85         pool.shutdown();
  86         if (! pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS))
  87             throw new Error();
  88    }
  89 
  90     static void oneTest(int producers, int iters) throws Exception {
  91         oneRun(new ArrayBlockingQueue<Integer>(CAPACITY), producers, iters);
  92         oneRun(new LinkedBlockingQueue<Integer>(CAPACITY), producers, iters);
  93         oneRun(new LinkedBlockingDeque<Integer>(CAPACITY), producers, iters);
  94         oneRun(new LinkedTransferQueue<Integer>(), producers, iters);
  95 
  96         // Don't run PBQ since can legitimately run out of memory
  97         //        if (print)
  98         //            System.out.print("PriorityBlockingQueue   ");
  99         //        oneRun(new PriorityBlockingQueue<Integer>(), producers, iters);
 100 
 101         oneRun(new SynchronousQueue<Integer>(), producers, iters);
 102         if (print)
 103             System.out.println("fair implementations:");
 104         oneRun(new SynchronousQueue<Integer>(true), producers, iters);
 105         oneRun(new ArrayBlockingQueue<Integer>(CAPACITY, true), producers, iters);
 106     }
 107 
 108     abstract static class Stage implements Runnable {
 109         final int iters;
 110         final BlockingQueue<Integer> queue;
 111         final CyclicBarrier barrier;
 112         Stage(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
 113             queue = q;
 114             barrier = b;
 115             this.iters = iters;
 116         }
 117     }
 118 
 119     static class Producer extends Stage {
 120         Producer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
 121             super(q, b, iters);
 122         }
 123 
 124         public void run() {
 125             try {
 126                 barrier.await();
 127                 int s = 0;
 128                 int l = hashCode();
 129                 for (int i = 0; i < iters; ++i) {
 130                     l = LoopHelpers.compute1(l);
 131                     l = LoopHelpers.compute2(l);
 132                     queue.put(new Integer(l));
 133                     s += l;
 134                 }
 135                 addProducerSum(s);
 136                 barrier.await();
 137             }
 138             catch (Exception ie) {
 139                 ie.printStackTrace();
 140                 return;
 141             }
 142         }
 143     }
 144 
 145     static class Consumer extends Stage {
 146         Consumer(BlockingQueue<Integer> q, CyclicBarrier b, int iters) {
 147             super(q, b, iters);
 148         }
 149 
 150         public void run() {
 151             try {
 152                 barrier.await();
 153                 int s = 0;
 154                 for (int i = 0; i < iters; ++i) {
 155                     s += queue.take().intValue();
 156                 }
 157                 addConsumerSum(s);
 158                 barrier.await();
 159             }
 160             catch (Exception ie) {
 161                 ie.printStackTrace();
 162                 return;
 163             }
 164         }
 165 
 166     }
 167 
 168     static void oneRun(BlockingQueue<Integer> q, int nproducers, int iters) throws Exception {
 169         if (print)
 170             System.out.printf("%-18s", q.getClass().getSimpleName());
 171         LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
 172         CyclicBarrier barrier = new CyclicBarrier(nproducers + 2, timer);
 173         for (int i = 0; i < nproducers; ++i) {
 174             pool.execute(new Producer(q, barrier, iters));
 175         }
 176         pool.execute(new Consumer(q, barrier, iters * nproducers));
 177         barrier.await();
 178         barrier.await();
 179         long time = timer.getTime();
 180         checkSum();
 181         if (print)
 182             System.out.println("\t: " + LoopHelpers.rightJustify(time / (iters * nproducers)) + " ns per transfer");
 183     }
 184 
 185 }