7 |
|
package jsr166y; |
8 |
|
|
9 |
|
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.atomic.*; |
10 |
> |
|
11 |
> |
import java.util.concurrent.atomic.AtomicReference; |
12 |
|
import java.util.concurrent.locks.LockSupport; |
12 |
– |
import sun.misc.Unsafe; |
13 |
– |
import java.lang.reflect.*; |
13 |
|
|
14 |
|
/** |
15 |
|
* A reusable synchronization barrier, similar in functionality to a |
92 |
|
* idiom is for the method setting this up to first register, then |
93 |
|
* start the actions, then deregister, as in: |
94 |
|
* |
95 |
< |
* <pre> |
96 |
< |
* void runTasks(List<Runnable> list) { |
97 |
< |
* final Phaser phaser = new Phaser(1); // "1" to register self |
98 |
< |
* for (Runnable r : list) { |
99 |
< |
* phaser.register(); |
100 |
< |
* new Thread() { |
101 |
< |
* public void run() { |
102 |
< |
* phaser.arriveAndAwaitAdvance(); // await all creation |
103 |
< |
* r.run(); |
104 |
< |
* phaser.arriveAndDeregister(); // signal completion |
105 |
< |
* } |
106 |
< |
* }.start(); |
95 |
> |
* <pre> {@code |
96 |
> |
* void runTasks(List<Runnable> list) { |
97 |
> |
* final Phaser phaser = new Phaser(1); // "1" to register self |
98 |
> |
* for (Runnable r : list) { |
99 |
> |
* phaser.register(); |
100 |
> |
* new Thread() { |
101 |
> |
* public void run() { |
102 |
> |
* phaser.arriveAndAwaitAdvance(); // await all creation |
103 |
> |
* r.run(); |
104 |
> |
* phaser.arriveAndDeregister(); // signal completion |
105 |
> |
* } |
106 |
> |
* }.start(); |
107 |
|
* } |
108 |
|
* |
109 |
|
* doSomethingOnBehalfOfWorkers(); |
112 |
|
* p = phaser.awaitAdvance(p); // ... and await arrival |
113 |
|
* otherActions(); // do other things while tasks execute |
114 |
|
* phaser.awaitAdvance(p); // await final completion |
115 |
< |
* } |
117 |
< |
* </pre> |
115 |
> |
* }}</pre> |
116 |
|
* |
117 |
|
* <p>One way to cause a set of threads to repeatedly perform actions |
118 |
|
* for a given number of iterations is to override {@code onAdvance}: |
119 |
|
* |
120 |
< |
* <pre> |
121 |
< |
* void startTasks(List<Runnable> list, final int iterations) { |
122 |
< |
* final Phaser phaser = new Phaser() { |
123 |
< |
* public boolean onAdvance(int phase, int registeredParties) { |
124 |
< |
* return phase >= iterations || registeredParties == 0; |
120 |
> |
* <pre> {@code |
121 |
> |
* void startTasks(List<Runnable> list, final int iterations) { |
122 |
> |
* final Phaser phaser = new Phaser() { |
123 |
> |
* public boolean onAdvance(int phase, int registeredParties) { |
124 |
> |
* return phase >= iterations || registeredParties == 0; |
125 |
> |
* } |
126 |
> |
* }; |
127 |
> |
* phaser.register(); |
128 |
> |
* for (Runnable r : list) { |
129 |
> |
* phaser.register(); |
130 |
> |
* new Thread() { |
131 |
> |
* public void run() { |
132 |
> |
* do { |
133 |
> |
* r.run(); |
134 |
> |
* phaser.arriveAndAwaitAdvance(); |
135 |
> |
* } while(!phaser.isTerminated(); |
136 |
|
* } |
137 |
< |
* }; |
129 |
< |
* phaser.register(); |
130 |
< |
* for (Runnable r : list) { |
131 |
< |
* phaser.register(); |
132 |
< |
* new Thread() { |
133 |
< |
* public void run() { |
134 |
< |
* do { |
135 |
< |
* r.run(); |
136 |
< |
* phaser.arriveAndAwaitAdvance(); |
137 |
< |
* } while(!phaser.isTerminated(); |
138 |
< |
* } |
139 |
< |
* }.start(); |
137 |
> |
* }.start(); |
138 |
|
* } |
139 |
|
* phaser.arriveAndDeregister(); // deregister self, don't wait |
140 |
< |
* } |
143 |
< |
* </pre> |
140 |
> |
* }}</pre> |
141 |
|
* |
142 |
|
* <p> To create a set of tasks using a tree of Phasers, |
143 |
|
* you could use code of the following form, assuming a |
144 |
|
* Task class with a constructor accepting a Phaser that |
145 |
|
* it registers for upon construction: |
146 |
< |
* <pre> |
147 |
< |
* void build(Task[] actions, int lo, int hi, Phaser b) { |
148 |
< |
* int step = (hi - lo) / TASKS_PER_PHASER; |
149 |
< |
* if (step > 1) { |
150 |
< |
* int i = lo; |
151 |
< |
* while (i < hi) { |
152 |
< |
* int r = Math.min(i + step, hi); |
153 |
< |
* build(actions, i, r, new Phaser(b)); |
154 |
< |
* i = r; |
155 |
< |
* } |
156 |
< |
* } |
157 |
< |
* else { |
158 |
< |
* for (int i = lo; i < hi; ++i) |
159 |
< |
* actions[i] = new Task(b); |
160 |
< |
* // assumes new Task(b) performs b.register() |
161 |
< |
* } |
162 |
< |
* } |
163 |
< |
* // .. initially called, for n tasks via |
167 |
< |
* build(new Task[n], 0, n, new Phaser()); |
168 |
< |
* </pre> |
146 |
> |
* <pre> {@code |
147 |
> |
* void build(Task[] actions, int lo, int hi, Phaser b) { |
148 |
> |
* int step = (hi - lo) / TASKS_PER_PHASER; |
149 |
> |
* if (step > 1) { |
150 |
> |
* int i = lo; |
151 |
> |
* while (i < hi) { |
152 |
> |
* int r = Math.min(i + step, hi); |
153 |
> |
* build(actions, i, r, new Phaser(b)); |
154 |
> |
* i = r; |
155 |
> |
* } |
156 |
> |
* } else { |
157 |
> |
* for (int i = lo; i < hi; ++i) |
158 |
> |
* actions[i] = new Task(b); |
159 |
> |
* // assumes new Task(b) performs b.register() |
160 |
> |
* } |
161 |
> |
* } |
162 |
> |
* // .. initially called, for n tasks via |
163 |
> |
* build(new Task[n], 0, n, new Phaser());}</pre> |
164 |
|
* |
165 |
|
* The best value of {@code TASKS_PER_PHASER} depends mainly on |
166 |
|
* expected barrier synchronization rates. A value as low as four may |
174 |
|
* parties result in IllegalStateExceptions. However, you can and |
175 |
|
* should create tiered phasers to accommodate arbitrarily large sets |
176 |
|
* of participants. |
177 |
+ |
* |
178 |
+ |
* @since 1.7 |
179 |
+ |
* @author Doug Lea |
180 |
|
*/ |
181 |
|
public class Phaser { |
182 |
|
/* |
210 |
|
private static final int phaseMask = 0x7fffffff; |
211 |
|
|
212 |
|
private static int unarrivedOf(long s) { |
213 |
< |
return (int)(s & ushortMask); |
213 |
> |
return (int) (s & ushortMask); |
214 |
|
} |
215 |
|
|
216 |
|
private static int partiesOf(long s) { |
217 |
< |
return ((int)s) >>> 16; |
217 |
> |
return ((int) s) >>> 16; |
218 |
|
} |
219 |
|
|
220 |
|
private static int phaseOf(long s) { |
221 |
< |
return (int)(s >>> 32); |
221 |
> |
return (int) (s >>> 32); |
222 |
|
} |
223 |
|
|
224 |
|
private static int arrivedOf(long s) { |
226 |
|
} |
227 |
|
|
228 |
|
private static long stateFor(int phase, int parties, int unarrived) { |
229 |
< |
return ((((long)phase) << 32) | (((long)parties) << 16) | |
230 |
< |
(long)unarrived); |
229 |
> |
return ((((long) phase) << 32) | (((long) parties) << 16) | |
230 |
> |
(long) unarrived); |
231 |
|
} |
232 |
|
|
233 |
|
private static long trippedStateFor(int phase, int parties) { |
234 |
< |
long lp = (long)parties; |
235 |
< |
return (((long)phase) << 32) | (lp << 16) | lp; |
234 |
> |
long lp = (long) parties; |
235 |
> |
return (((long) phase) << 32) | (lp << 16) | lp; |
236 |
|
} |
237 |
|
|
238 |
|
/** |
239 |
< |
* Returns message string for bad bounds exceptions |
239 |
> |
* Returns message string for bad bounds exceptions. |
240 |
|
*/ |
241 |
|
private static String badBounds(int parties, int unarrived) { |
242 |
|
return ("Attempt to set " + unarrived + |
265 |
|
private final AtomicReference<QNode> oddQ = new AtomicReference<QNode>(); |
266 |
|
|
267 |
|
private AtomicReference<QNode> queueFor(int phase) { |
268 |
< |
return (phase & 1) == 0? evenQ : oddQ; |
268 |
> |
return ((phase & 1) == 0) ? evenQ : oddQ; |
269 |
|
} |
270 |
|
|
271 |
|
/** |
273 |
|
* root if necessary. |
274 |
|
*/ |
275 |
|
private long getReconciledState() { |
276 |
< |
return parent == null? state : reconcileState(); |
276 |
> |
return (parent == null) ? state : reconcileState(); |
277 |
|
} |
278 |
|
|
279 |
|
/** |
311 |
|
/** |
312 |
|
* Creates a new Phaser with the given numbers of registered |
313 |
|
* unarrived parties, initial phase number 0, and no parent. |
314 |
< |
* @param parties the number of parties required to trip barrier. |
314 |
> |
* |
315 |
> |
* @param parties the number of parties required to trip barrier |
316 |
|
* @throws IllegalArgumentException if parties less than zero |
317 |
< |
* or greater than the maximum number of parties supported. |
317 |
> |
* or greater than the maximum number of parties supported |
318 |
|
*/ |
319 |
|
public Phaser(int parties) { |
320 |
|
this(null, parties); |
325 |
|
* initially registered parties. If parent is non-null this phaser |
326 |
|
* is registered with the parent and its initial phase number is |
327 |
|
* the same as that of parent phaser. |
328 |
< |
* @param parent the parent phaser. |
328 |
> |
* |
329 |
> |
* @param parent the parent phaser |
330 |
|
*/ |
331 |
|
public Phaser(Phaser parent) { |
332 |
|
int phase = 0; |
342 |
|
|
343 |
|
/** |
344 |
|
* Creates a new Phaser with the given parent and numbers of |
345 |
< |
* registered unarrived parties. If parent is non-null this phaser |
345 |
> |
* registered unarrived parties. If parent is non-null, this phaser |
346 |
|
* is registered with the parent and its initial phase number is |
347 |
|
* the same as that of parent phaser. |
348 |
< |
* @param parent the parent phaser. |
349 |
< |
* @param parties the number of parties required to trip barrier. |
348 |
> |
* |
349 |
> |
* @param parent the parent phaser |
350 |
> |
* @param parties the number of parties required to trip barrier |
351 |
|
* @throws IllegalArgumentException if parties less than zero |
352 |
< |
* or greater than the maximum number of parties supported. |
352 |
> |
* or greater than the maximum number of parties supported |
353 |
|
*/ |
354 |
|
public Phaser(Phaser parent, int parties) { |
355 |
|
if (parties < 0 || parties > ushortMask) |
367 |
|
|
368 |
|
/** |
369 |
|
* Adds a new unarrived party to this phaser. |
370 |
+ |
* |
371 |
|
* @return the current barrier phase number upon registration |
372 |
|
* @throws IllegalStateException if attempting to register more |
373 |
< |
* than the maximum supported number of parties. |
373 |
> |
* than the maximum supported number of parties |
374 |
|
*/ |
375 |
|
public int register() { |
376 |
|
return doRegister(1); |
378 |
|
|
379 |
|
/** |
380 |
|
* Adds the given number of new unarrived parties to this phaser. |
381 |
< |
* @param parties the number of parties required to trip barrier. |
381 |
> |
* |
382 |
> |
* @param parties the number of parties required to trip barrier |
383 |
|
* @return the current barrier phase number upon registration |
384 |
|
* @throws IllegalStateException if attempting to register more |
385 |
< |
* than the maximum supported number of parties. |
385 |
> |
* than the maximum supported number of parties |
386 |
|
*/ |
387 |
|
public int bulkRegister(int parties) { |
388 |
|
if (parties < 0) |
402 |
|
phase = phaseOf(s); |
403 |
|
int unarrived = unarrivedOf(s) + registrations; |
404 |
|
int parties = partiesOf(s) + registrations; |
405 |
< |
if (phase < 0) |
405 |
> |
if (phase < 0) |
406 |
|
break; |
407 |
|
if (parties > ushortMask || unarrived > ushortMask) |
408 |
|
throw new IllegalStateException(badBounds(parties, unarrived)); |
418 |
|
* in turn wait for others via {@link #awaitAdvance}). |
419 |
|
* |
420 |
|
* @return the barrier phase number upon entry to this method, or a |
421 |
< |
* negative value if terminated; |
421 |
> |
* negative value if terminated |
422 |
|
* @throws IllegalStateException if not terminated and the number |
423 |
< |
* of unarrived parties would become negative. |
423 |
> |
* of unarrived parties would become negative |
424 |
|
*/ |
425 |
|
public int arrive() { |
426 |
|
int phase; |
440 |
|
if (par == null) { // directly trip |
441 |
|
if (casState |
442 |
|
(s, |
443 |
< |
trippedStateFor(onAdvance(phase, parties)? -1 : |
443 |
> |
trippedStateFor(onAdvance(phase, parties) ? -1 : |
444 |
|
((phase + 1) & phaseMask), parties))) { |
445 |
|
releaseWaiters(phase); |
446 |
|
break; |
470 |
|
* zero parties, this phaser is also deregistered from its parent. |
471 |
|
* |
472 |
|
* @return the current barrier phase number upon entry to |
473 |
< |
* this method, or a negative value if terminated; |
473 |
> |
* this method, or a negative value if terminated |
474 |
|
* @throws IllegalStateException if not terminated and the number |
475 |
< |
* of registered or unarrived parties would become negative. |
475 |
> |
* of registered or unarrived parties would become negative |
476 |
|
*/ |
477 |
|
public int arriveAndDeregister() { |
478 |
|
// similar code to arrive, but too different to merge |
501 |
|
if (unarrived == 0) { |
502 |
|
if (casState |
503 |
|
(s, |
504 |
< |
trippedStateFor(onAdvance(phase, parties)? -1 : |
504 |
> |
trippedStateFor(onAdvance(phase, parties) ? -1 : |
505 |
|
((phase + 1) & phaseMask), parties))) { |
506 |
|
releaseWaiters(phase); |
507 |
|
break; |
523 |
|
* to {@code awaitAdvance(arrive())}. If you instead need to |
524 |
|
* await with interruption of timeout, and/or deregister upon |
525 |
|
* arrival, you can arrange them using analogous constructions. |
526 |
+ |
* |
527 |
|
* @return the phase on entry to this method |
528 |
|
* @throws IllegalStateException if not terminated and the number |
529 |
< |
* of unarrived parties would become negative. |
529 |
> |
* of unarrived parties would become negative |
530 |
|
*/ |
531 |
|
public int arriveAndAwaitAdvance() { |
532 |
|
return awaitAdvance(arrive()); |
536 |
|
* Awaits the phase of the barrier to advance from the given |
537 |
|
* value, or returns immediately if argument is negative or this |
538 |
|
* barrier is terminated. |
539 |
+ |
* |
540 |
|
* @param phase the phase on entry to this method |
541 |
|
* @return the phase on exit from this method |
542 |
|
*/ |
558 |
|
* value, or returns immediately if argument is negative or this |
559 |
|
* barrier is terminated, or throws InterruptedException if |
560 |
|
* interrupted while waiting. |
561 |
+ |
* |
562 |
|
* @param phase the phase on entry to this method |
563 |
|
* @return the phase on exit from this method |
564 |
|
* @throws InterruptedException if thread interrupted while waiting |
565 |
|
*/ |
566 |
< |
public int awaitAdvanceInterruptibly(int phase) |
566 |
> |
public int awaitAdvanceInterruptibly(int phase) |
567 |
|
throws InterruptedException { |
568 |
|
if (phase < 0) |
569 |
|
return phase; |
580 |
|
* Awaits the phase of the barrier to advance from the given value |
581 |
|
* or the given timeout elapses, or returns immediately if |
582 |
|
* argument is negative or this barrier is terminated. |
583 |
+ |
* |
584 |
|
* @param phase the phase on entry to this method |
585 |
|
* @return the phase on exit from this method |
586 |
|
* @throws InterruptedException if thread interrupted while waiting |
587 |
|
* @throws TimeoutException if timed out while waiting |
588 |
|
*/ |
589 |
< |
public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit) |
589 |
> |
public int awaitAdvanceInterruptibly(int phase, |
590 |
> |
long timeout, TimeUnit unit) |
591 |
|
throws InterruptedException, TimeoutException { |
592 |
|
if (phase < 0) |
593 |
|
return phase; |
628 |
|
* Returns the current phase number. The maximum phase number is |
629 |
|
* {@code Integer.MAX_VALUE}, after which it restarts at |
630 |
|
* zero. Upon termination, the phase number is negative. |
631 |
+ |
* |
632 |
|
* @return the phase number, or a negative value if terminated |
633 |
|
*/ |
634 |
|
public final int getPhase() { |
637 |
|
|
638 |
|
/** |
639 |
|
* Returns {@code true} if the current phase number equals the given phase. |
640 |
+ |
* |
641 |
|
* @param phase the phase |
642 |
|
* @return {@code true} if the current phase number equals the given phase |
643 |
|
*/ |
647 |
|
|
648 |
|
/** |
649 |
|
* Returns the number of parties registered at this barrier. |
650 |
+ |
* |
651 |
|
* @return the number of parties |
652 |
|
*/ |
653 |
|
public int getRegisteredParties() { |
657 |
|
/** |
658 |
|
* Returns the number of parties that have arrived at the current |
659 |
|
* phase of this barrier. |
660 |
+ |
* |
661 |
|
* @return the number of arrived parties |
662 |
|
*/ |
663 |
|
public int getArrivedParties() { |
667 |
|
/** |
668 |
|
* Returns the number of registered parties that have not yet |
669 |
|
* arrived at the current phase of this barrier. |
670 |
+ |
* |
671 |
|
* @return the number of unarrived parties |
672 |
|
*/ |
673 |
|
public int getUnarrivedParties() { |
676 |
|
|
677 |
|
/** |
678 |
|
* Returns the parent of this phaser, or null if none. |
679 |
+ |
* |
680 |
|
* @return the parent of this phaser, or null if none |
681 |
|
*/ |
682 |
|
public Phaser getParent() { |
686 |
|
/** |
687 |
|
* Returns the root ancestor of this phaser, which is the same as |
688 |
|
* this phaser if it has no parent. |
689 |
+ |
* |
690 |
|
* @return the root ancestor of this phaser |
691 |
|
*/ |
692 |
|
public Phaser getRoot() { |
695 |
|
|
696 |
|
/** |
697 |
|
* Returns {@code true} if this barrier has been terminated. |
698 |
+ |
* |
699 |
|
* @return {@code true} if this barrier has been terminated |
700 |
|
*/ |
701 |
|
public boolean isTerminated() { |
811 |
|
try { |
812 |
|
ForkJoinPool.managedBlock(this, false); |
813 |
|
} catch (InterruptedException ie) { |
814 |
< |
} |
814 |
> |
} |
815 |
|
} |
816 |
|
return wasInterrupted; |
817 |
|
} |
819 |
|
} |
820 |
|
|
821 |
|
/** |
822 |
< |
* Removes and signals waiting threads from wait queue |
822 |
> |
* Removes and signals waiting threads from wait queue. |
823 |
|
*/ |
824 |
|
private void releaseWaiters(int phase) { |
825 |
|
AtomicReference<QNode> head = queueFor(phase); |
831 |
|
} |
832 |
|
|
833 |
|
/** |
834 |
< |
* Tries to enqueue given node in the appropriate wait queue |
834 |
> |
* Tries to enqueue given node in the appropriate wait queue. |
835 |
> |
* |
836 |
|
* @return true if successful |
837 |
|
*/ |
838 |
|
private boolean tryEnqueue(QNode node) { |
842 |
|
|
843 |
|
/** |
844 |
|
* Enqueues node and waits unless aborted or signalled. |
845 |
+ |
* |
846 |
|
* @return current phase |
847 |
|
*/ |
848 |
|
private int untimedWait(int phase) { |
930 |
|
return p; |
931 |
|
} |
932 |
|
|
933 |
< |
// Temporary Unsafe mechanics for preliminary release |
934 |
< |
private static Unsafe getUnsafe() throws Throwable { |
933 |
> |
// Unsafe mechanics for jsr166y 3rd party package. |
934 |
> |
private static sun.misc.Unsafe getUnsafe() { |
935 |
|
try { |
936 |
< |
return Unsafe.getUnsafe(); |
936 |
> |
return sun.misc.Unsafe.getUnsafe(); |
937 |
|
} catch (SecurityException se) { |
938 |
|
try { |
939 |
|
return java.security.AccessController.doPrivileged |
940 |
< |
(new java.security.PrivilegedExceptionAction<Unsafe>() { |
941 |
< |
public Unsafe run() throws Exception { |
942 |
< |
return getUnsafePrivileged(); |
940 |
> |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
941 |
> |
public sun.misc.Unsafe run() throws Exception { |
942 |
> |
return getUnsafeByReflection(); |
943 |
|
}}); |
944 |
|
} catch (java.security.PrivilegedActionException e) { |
945 |
< |
throw e.getCause(); |
945 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
946 |
> |
e.getCause()); |
947 |
|
} |
948 |
|
} |
949 |
|
} |
950 |
|
|
951 |
< |
private static Unsafe getUnsafePrivileged() |
951 |
> |
private static sun.misc.Unsafe getUnsafeByReflection() |
952 |
|
throws NoSuchFieldException, IllegalAccessException { |
953 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
953 |
> |
java.lang.reflect.Field f = |
954 |
> |
sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); |
955 |
|
f.setAccessible(true); |
956 |
< |
return (Unsafe)f.get(null); |
956 |
> |
return (sun.misc.Unsafe) f.get(null); |
957 |
|
} |
958 |
|
|
959 |
< |
private static long fieldOffset(String fieldName) |
940 |
< |
throws NoSuchFieldException { |
941 |
< |
return _unsafe.objectFieldOffset |
942 |
< |
(Phaser.class.getDeclaredField(fieldName)); |
943 |
< |
} |
944 |
< |
|
945 |
< |
static final Unsafe _unsafe; |
946 |
< |
static final long stateOffset; |
947 |
< |
|
948 |
< |
static { |
959 |
> |
private static long fieldOffset(String fieldName, Class<?> klazz) { |
960 |
|
try { |
961 |
< |
_unsafe = getUnsafe(); |
962 |
< |
stateOffset = fieldOffset("state"); |
963 |
< |
} catch (Exception e) { |
964 |
< |
throw new RuntimeException("Could not initialize intrinsics", e); |
961 |
> |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName)); |
962 |
> |
} catch (NoSuchFieldException e) { |
963 |
> |
// Convert Exception to Error |
964 |
> |
NoSuchFieldError error = new NoSuchFieldError(fieldName); |
965 |
> |
error.initCause(e); |
966 |
> |
throw error; |
967 |
|
} |
968 |
|
} |
969 |
|
|
970 |
+ |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
971 |
+ |
static final long stateOffset = |
972 |
+ |
fieldOffset("state", Phaser.class); |
973 |
+ |
|
974 |
|
final boolean casState(long cmp, long val) { |
975 |
< |
return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val); |
975 |
> |
return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val); |
976 |
|
} |
977 |
|
} |