/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

import java.util.*;
import java.util.concurrent.*;

public class SPL7 {
    static final int ITEMS = 1 << 20;
    static final int CONSUMERS  = 64; // 100;
    static final int CAP        = Flow.defaultBufferSize();

    static final Phaser phaser = new Phaser(CONSUMERS + 1);

    static class Sub implements Flow.Subscriber<Integer> {
        Flow.Subscription sn;
        int count;
        public void onSubscribe(Flow.Subscription s) { 
            (sn = s).request(CAP); 
        }
        public void onNext(Integer t) { 
            if ((++count & (CAP - 1)) == (CAP >>> 1))
                sn.request(CAP);
            //            consumeCPU(10000); 
        }
        public void onError(Throwable t) { t.printStackTrace(); }
        public void onComplete() { 
            if (count != ITEMS)
                System.out.println("Error: remaining " + (ITEMS - count));
            phaser.arrive(); 
        }
    }

    static final long NPS = (1000L * 1000 * 1000);

    public static void main(String[] args) throws Exception {
        System.out.println("ITEMS " + ITEMS);
        //        ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() - 1);
        ExecutorService exec = ForkJoinPool.commonPool();
        for (int reps = 0; reps < 9; ++reps) {
            long startTime = System.nanoTime();
            final SubmissionPublisher<Integer> pub = 
                new SubmissionPublisher<Integer>(exec, CAP);
            for (int i = 0; i < CONSUMERS; ++i)
                pub.subscribe(new Sub());
            for (int i = 0; i < ITEMS; ++i) {
                pub.submit(new Integer(i));
            }
            pub.close();
            phaser.arriveAndAwaitAdvance();
            long elapsed = System.nanoTime() - startTime;
            double secs = ((double)elapsed) / NPS;
            System.out.printf("\tTime: %7.3f\n", secs);
            System.out.println(exec); // ForkJoinPool.commonPool());
            Thread.sleep(1000);
        }
        if (exec != ForkJoinPool.commonPool())
            exec.shutdown();
    }
    private static volatile long consumedCPU = System.nanoTime(); 
    static void consumeCPU(long tokens) { // Taken from JMH blackhole
        long t = consumedCPU;
        for (long i = tokens; i > 0; i--) {
            t += (t * 0x5DEECE66DL + 0xBL + i) & (0xFFFFFFFFFFFFL);
        }
        if (t == 42) {
            consumedCPU += t;
        }
    }
}
