1 |
dl |
1.1 |
/* |
2 |
|
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
|
* Expert Group and released to the public domain, as explained at |
4 |
|
|
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
|
*/ |
6 |
|
|
|
7 |
|
|
import java.util.*; |
8 |
|
|
import java.util.concurrent.*; |
9 |
|
|
|
10 |
|
|
/** |
11 |
|
|
* One publisher, many subscribers |
12 |
|
|
*/ |
13 |
|
|
public class SubmissionPublisherLoops1 { |
14 |
|
|
static final int ITEMS = 1 << 20; |
15 |
|
|
static final int CONSUMERS = 64; |
16 |
|
|
static final int CAP = Flow.defaultBufferSize(); |
17 |
|
|
static final int REPS = 9; |
18 |
|
|
|
19 |
|
|
static final Phaser phaser = new Phaser(CONSUMERS + 1); |
20 |
|
|
|
21 |
dl |
1.4 |
static final class Sub implements Flow.Subscriber<Boolean> { |
22 |
dl |
1.1 |
Flow.Subscription sn; |
23 |
|
|
int count; |
24 |
jsr166 |
1.2 |
public void onSubscribe(Flow.Subscription s) { |
25 |
|
|
(sn = s).request(CAP); |
26 |
dl |
1.1 |
} |
27 |
jsr166 |
1.2 |
public void onNext(Boolean t) { |
28 |
dl |
1.1 |
if ((++count & (CAP - 1)) == (CAP >>> 1)) |
29 |
|
|
sn.request(CAP); |
30 |
|
|
} |
31 |
|
|
public void onError(Throwable t) { t.printStackTrace(); } |
32 |
jsr166 |
1.2 |
public void onComplete() { |
33 |
dl |
1.1 |
if (count != ITEMS) |
34 |
|
|
System.out.println("Error: remaining " + (ITEMS - count)); |
35 |
jsr166 |
1.2 |
phaser.arrive(); |
36 |
dl |
1.1 |
} |
37 |
|
|
} |
38 |
|
|
|
39 |
|
|
static final long NPS = (1000L * 1000 * 1000); |
40 |
|
|
|
41 |
|
|
public static void main(String[] args) throws Exception { |
42 |
|
|
int reps = REPS; |
43 |
|
|
if (args.length > 0) |
44 |
|
|
reps = Integer.parseInt(args[0]); |
45 |
jsr166 |
1.2 |
|
46 |
|
|
System.out.println("ITEMS: " + ITEMS + |
47 |
dl |
1.1 |
" CONSUMERS: " + CONSUMERS + |
48 |
|
|
" CAP: " + CAP); |
49 |
|
|
ExecutorService exec = ForkJoinPool.commonPool(); |
50 |
dl |
1.3 |
for (int rep = 0; rep < reps; ++rep) { |
51 |
dl |
1.4 |
oneRun(exec); |
52 |
dl |
1.1 |
Thread.sleep(1000); |
53 |
|
|
} |
54 |
|
|
if (exec != ForkJoinPool.commonPool()) |
55 |
|
|
exec.shutdown(); |
56 |
|
|
} |
57 |
dl |
1.4 |
|
58 |
|
|
static void oneRun(ExecutorService exec) throws Exception { |
59 |
|
|
long startTime = System.nanoTime(); |
60 |
|
|
final SubmissionPublisher<Boolean> pub = |
61 |
|
|
new SubmissionPublisher<Boolean>(exec, CAP); |
62 |
|
|
for (int i = 0; i < CONSUMERS; ++i) |
63 |
|
|
pub.subscribe(new Sub()); |
64 |
|
|
for (int i = 0; i < ITEMS; ++i) { |
65 |
|
|
pub.submit(Boolean.TRUE); |
66 |
|
|
} |
67 |
|
|
pub.close(); |
68 |
|
|
phaser.arriveAndAwaitAdvance(); |
69 |
|
|
long elapsed = System.nanoTime() - startTime; |
70 |
|
|
double secs = ((double)elapsed) / NPS; |
71 |
|
|
System.out.printf("\tTime: %7.3f\n", secs); |
72 |
|
|
} |
73 |
dl |
1.1 |
} |