-
Notifications
You must be signed in to change notification settings - Fork 220
/
Basic.java
465 lines (426 loc) · 18.8 KB
/
Basic.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* 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/
*/
/*
* @test
* @bug 6445158
* @summary Basic tests for Phaser
* @author Chris Hegarty
* @modules java.management
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
public class Basic {
private static void checkTerminated(final Phaser phaser) {
check(phaser.isTerminated());
int unarriverParties = phaser.getUnarrivedParties();
int registeredParties = phaser.getRegisteredParties();
int phase = phaser.getPhase();
check(phase < 0);
equal(phase, phaser.arrive());
equal(phase, phaser.arriveAndDeregister());
equal(phase, phaser.arriveAndAwaitAdvance());
equal(phase, phaser.bulkRegister(10));
equal(phase, phaser.register());
try {
equal(phase, phaser.awaitAdvanceInterruptibly(0));
equal(phase, phaser.awaitAdvanceInterruptibly(0, 10, SECONDS));
} catch (Exception ex) {
unexpected(ex);
}
equal(phaser.getUnarrivedParties(), unarriverParties);
equal(phaser.getRegisteredParties(), registeredParties);
}
private static void checkResult(Arriver a, Class<? extends Throwable> c) {
Throwable t = a.result();
if (! ((t == null && c == null) || (c != null && c.isInstance(t)))) {
// t.printStackTrace();
fail("Mismatch in thread " +
a.getName() + ": " +
t + ", " +
(c == null ? "<null>" : c.getName()));
} else {
pass();
}
}
//----------------------------------------------------------------
// Mechanism to get all test threads into "running" mode.
//----------------------------------------------------------------
private static Phaser startingGate = new Phaser(3);
private static void toTheStartingGate() {
try {
boolean expectNextPhase = (startingGate.getUnarrivedParties() == 1);
int phase = startingGate.getPhase();
equal(phase, startingGate.arrive());
int awaitPhase;
for (boolean interrupted = false;;) {
try {
awaitPhase = startingGate.awaitAdvanceInterruptibly
(phase, 30, SECONDS);
if (interrupted) Thread.currentThread().interrupt();
break;
} catch (InterruptedException ie) {
interrupted = true;
}
}
if (expectNextPhase) check(awaitPhase == phase + 1);
else check(awaitPhase == phase || awaitPhase == phase + 1);
pass();
} catch (Throwable t) {
unexpected(t);
// reset(startingGate);
throw new Error(t);
}
}
//----------------------------------------------------------------
// Convenience methods for creating threads that call arrive,
// awaitAdvance, arriveAndAwaitAdvance, awaitAdvanceInterruptibly
//----------------------------------------------------------------
private abstract static class Arriver extends Thread {
static AtomicInteger count = new AtomicInteger(1);
Arriver() {
this("Arriver");
}
Arriver(String name) {
this.setName(name + ":" + count.getAndIncrement());
this.setDaemon(true);
}
private volatile Throwable result;
private volatile int phase;
protected void result(Throwable result) { this.result = result; }
public Throwable result() { return this.result; }
protected void phase(int phase) { this.phase = phase; }
public int phase() { return this.phase; }
}
private abstract static class Awaiter extends Arriver {
Awaiter() { super("Awaiter"); }
Awaiter(String name) { super(name); }
}
private static Arriver arriver(final Phaser phaser) {
return new Arriver() { public void run() {
toTheStartingGate();
try { phase(phaser.arrive()); }
catch (Throwable result) { result(result); }}};
}
private static AtomicInteger cycleArriveAwaitAdvance = new AtomicInteger(1);
private static Awaiter awaiter(final Phaser phaser) {
return new Awaiter() { public void run() {
toTheStartingGate();
try {
if (cycleArriveAwaitAdvance.getAndIncrement() % 2 == 0)
phase(phaser.awaitAdvance(phaser.arrive()));
else
phase(phaser.arriveAndAwaitAdvance());
} catch (Throwable result) { result(result); }}};
}
private static Awaiter awaiter(final Phaser phaser,
final long timeout,
final TimeUnit unit) {
return new Awaiter("InterruptibleWaiter") { public void run() {
toTheStartingGate();
try {
if (timeout < 0)
phase(phaser.awaitAdvanceInterruptibly(phaser.arrive()));
else
phase(phaser.awaitAdvanceInterruptibly(phaser.arrive(),
timeout,
unit));
} catch (Throwable result) { result(result); }}};
}
// Returns an infinite lazy list of all possible arriver/awaiter combinations.
private static Iterator<Arriver> arriverIterator(final Phaser phaser) {
return new Iterator<Arriver>() {
int i = 0;
public boolean hasNext() { return true; }
public Arriver next() {
switch ((i++)&7) {
case 0: case 4:
return arriver(phaser);
case 1: case 5:
return awaiter(phaser);
case 2: case 6: case 7:
return awaiter(phaser, -1, SECONDS);
default:
return awaiter(phaser, 30, SECONDS); }}
public void remove() {throw new UnsupportedOperationException();}};
}
// Returns an infinite lazy list of all possible awaiter only combinations.
private static Iterator<Awaiter> awaiterIterator(final Phaser phaser) {
return new Iterator<Awaiter>() {
int i = 0;
public boolean hasNext() { return true; }
public Awaiter next() {
switch ((i++)&7) {
case 1: case 4: case 7:
return awaiter(phaser);
case 2: case 5:
return awaiter(phaser, -1, SECONDS);
default:
return awaiter(phaser, 30, SECONDS); }}
public void remove() {throw new UnsupportedOperationException();}};
}
static class SimpleTimer {
long startTime = System.nanoTime();
long elapsedMillis() {
long now = System.nanoTime();
long elapsed = NANOSECONDS.toMillis(now - startTime);
startTime = now;
return elapsed;
}
void printElapsed() { System.out.println(elapsedMillis() + " ms"); }
}
private static void realMain(String[] args) throws Throwable {
SimpleTimer timer = new SimpleTimer();
Thread.currentThread().setName("mainThread");
//----------------------------------------------------------------
System.out.print("Normal use: ");
//----------------------------------------------------------------
try {
Phaser phaser = new Phaser(3);
equal(phaser.getRegisteredParties(), 3);
equal(phaser.getArrivedParties(), 0);
equal(phaser.getPhase(), 0);
check(phaser.getRoot().equals(phaser));
equal(phaser.getParent(), null);
check(!phaser.isTerminated());
Iterator<Arriver> arrivers = arriverIterator(phaser);
int phase = 0;
for (int i = 0; i < 10; i++) {
equal(phaser.getPhase(), phase++);
Arriver a1 = arrivers.next(); a1.start();
Arriver a2 = arrivers.next(); a2.start();
toTheStartingGate();
phaser.arriveAndAwaitAdvance();
a1.join();
a2.join();
checkResult(a1, null);
checkResult(a2, null);
check(!phaser.isTerminated());
equal(phaser.getRegisteredParties(), 3);
equal(phaser.getArrivedParties(), 0);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
System.out.print("One thread interrupted: ");
//----------------------------------------------------------------
try {
Phaser phaser = new Phaser(3);
Iterator<Arriver> arrivers = arriverIterator(phaser);
int phase = phaser.getPhase();
for (int i = 0; i < 10; i++) {
check(phaser.getPhase() == phase);
Awaiter a1 = awaiter(phaser, 30, SECONDS); a1.start();
Arriver a2 = arrivers.next(); a2.start();
toTheStartingGate();
a1.interrupt();
a1.join();
phaser.arriveAndAwaitAdvance();
a2.join();
checkResult(a1, InterruptedException.class);
checkResult(a2, null);
check(!phaser.isTerminated());
equal(phaser.getRegisteredParties(), 3);
equal(phaser.getArrivedParties(), 0);
phase++;
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
System.out.print("Phaser is terminated while threads are waiting: ");
//----------------------------------------------------------------
try {
for (int i = 0; i < 10; i++) {
Phaser phaser = new Phaser(3);
Iterator<Awaiter> awaiters = awaiterIterator(phaser);
Arriver a1 = awaiters.next(); a1.start();
Arriver a2 = awaiters.next(); a2.start();
toTheStartingGate();
while (phaser.getArrivedParties() < 2) Thread.yield();
equal(0, phaser.getPhase());
phaser.forceTermination();
a1.join();
a2.join();
equal(0 + Integer.MIN_VALUE, a1.phase);
equal(0 + Integer.MIN_VALUE, a2.phase);
int arrivedParties = phaser.getArrivedParties();
checkTerminated(phaser);
equal(phaser.getArrivedParties(), arrivedParties);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
System.out.print("Adds new unarrived parties to this phaser: ");
//----------------------------------------------------------------
try {
Phaser phaser = new Phaser(1);
Iterator<Arriver> arrivers = arriverIterator(phaser);
LinkedList<Arriver> arriverList = new LinkedList<>();
int phase = phaser.getPhase();
for (int i = 1; i < 5; i++) {
startingGate = new Phaser(1+(3*i));
check(phaser.getPhase() == phase);
// register 3 more
phaser.register(); phaser.register(); phaser.register();
for (int z=0; z<(3*i); z++) {
arriverList.add(arrivers.next());
}
for (Arriver arriver : arriverList)
arriver.start();
toTheStartingGate();
phaser.arriveAndAwaitAdvance();
for (Arriver arriver : arriverList) {
arriver.join();
checkResult(arriver, null);
}
equal(phaser.getRegisteredParties(), 1 + (3*i));
equal(phaser.getArrivedParties(), 0);
arriverList.clear();
phase++;
}
startingGate = new Phaser(3);
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
System.out.print("One thread timed out: ");
//----------------------------------------------------------------
try {
Phaser phaser = new Phaser(3);
Iterator<Arriver> arrivers = arriverIterator(phaser);
for (long timeout : new long[] { 0L, 12L }) {
Awaiter a1 = awaiter(phaser, timeout, MILLISECONDS);
a1.start();
Arriver a2 = arrivers.next();
a2.start();
toTheStartingGate();
a1.join();
checkResult(a1, TimeoutException.class);
phaser.arrive();
a2.join();
checkResult(a2, null);
check(!phaser.isTerminated());
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
//----------------------------------------------------------------
System.out.print("Barrier action completed normally: ");
//----------------------------------------------------------------
try {
final AtomicInteger count = new AtomicInteger(0);
final Phaser[] kludge = new Phaser[1];
Phaser phaser = new Phaser(3) {
@Override
protected boolean onAdvance(int phase, int registeredParties) {
int countPhase = count.getAndIncrement();
equal(countPhase, phase);
equal(kludge[0].getPhase(), phase);
equal(kludge[0].getRegisteredParties(), registeredParties);
if (phase >= 3)
return true; // terminate
return false;
}
};
kludge[0] = phaser;
equal(phaser.getRegisteredParties(), 3);
Iterator<Awaiter> awaiters = awaiterIterator(phaser);
for (int i = 0; i < 4; i++) {
Awaiter a1 = awaiters.next(); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
while (phaser.getArrivedParties() < 2) Thread.yield();
phaser.arrive();
a1.join();
a2.join();
checkResult(a1, null);
checkResult(a2, null);
equal(count.get(), i+1);
if (i < 3) {
check(!phaser.isTerminated());
equal(phaser.getRegisteredParties(), 3);
equal(phaser.getArrivedParties(), 0);
equal(phaser.getUnarrivedParties(), 3);
equal(phaser.getPhase(), count.get());
} else
checkTerminated(phaser);
}
} catch (Throwable t) { unexpected(t); }
timer.printElapsed();
}
//--------------------- Infrastructure ---------------------------
/**
* A debugging tool to print stack traces of most threads, as jstack does.
* Uninteresting threads are filtered out.
*/
static void dumpTestThreads() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
System.err.println("------ stacktrace dump start ------");
for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
String name = info.getThreadName();
if ("Signal Dispatcher".equals(name))
continue;
if ("Reference Handler".equals(name)
&& info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
continue;
if ("Finalizer".equals(name)
&& info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
continue;
if (name.startsWith("process reaper"))
continue;
if (name != null && name.startsWith("ForkJoinPool.commonPool-worker"))
continue;
System.err.print(info);
}
System.err.println("------ stacktrace dump end ------");
}
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; Thread.dumpStack();}
static void fail(String msg) {System.out.println(msg); fail();}
static void unexpected(Throwable t) {failed++; t.printStackTrace(); dumpTestThreads();}
static void check(boolean cond) {if (cond) pass(); else fail();}
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}