comparison src/classes/java/util/concurrent/CyclicBarrier.java @ 0:61d41facf527

initial v8 import (history reset)
author Peter Mehlitz <Peter.C.Mehlitz@nasa.gov>
date Fri, 23 Jan 2015 10:14:01 -0800
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:61d41facf527
1 /*
2 * Copyright (C) 2014, United States Government, as represented by the
3 * Administrator of the National Aeronautics and Space Administration.
4 * All rights reserved.
5 *
6 * The Java Pathfinder core (jpf-core) platform is licensed under the
7 * Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0.
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package java.util.concurrent;
19
20 /**
21 * a simplistic CyclicBarrier implementation, required because the real one
22 * relies heavily on Sun infrastructure (including native methods)
23 */
24 public class CyclicBarrier {
25
26 private Runnable action;
27 private int parties;
28 private int count;
29 private boolean isBroken;
30
31 // make sure nobody from the outside can interfere with our locking
32 private final Object lock = new Object();
33
34
35 public CyclicBarrier (int parties) {
36 this(parties, null);
37 }
38
39 public CyclicBarrier (int parties, Runnable action) {
40 this.parties = parties;
41 count = parties;
42
43 this.action = action;
44 }
45
46 public int await () throws InterruptedException, BrokenBarrierException {
47 synchronized (lock) {
48 int arrival = parties - count;
49
50 if (--count == 0) {
51 if (action != null) {
52 action.run();
53 }
54 count = parties; // reset barrier
55 lock.notifyAll();
56 } else {
57 try {
58 lock.wait();
59 if (isBroken) {
60 throw new BrokenBarrierException();
61 }
62 } catch (InterruptedException ix) {
63 if (count > 0) {
64 isBroken = true;
65 lock.notifyAll();
66 }
67
68 throw ix;
69 }
70 }
71
72 return arrival;
73 }
74 }
75
76 public int getParties () {
77 return parties;
78 }
79
80 public void reset () {
81 synchronized (lock) {
82 if ((count != parties) && (count != 0)) {
83 // there are waiters
84 isBroken = true;
85 lock.notifyAll();
86 } else {
87 count = parties;
88 isBroken = false;
89 }
90 }
91 }
92
93 public boolean isBroken () {
94 // true if one of the parties got out of an await by being
95 // interrupted
96 return isBroken;
97 }
98
99 public int getNumberWaiting () {
100 synchronized (lock) {
101 return (parties - count);
102 }
103 }
104 }