Skip to content

Commit 9b26727

Browse files
committed
verify that all the threads are waiting, don't rely on the count of threads
Since the same thread might call await() more than once, relying on just the count may lead to inaccuracies.
1 parent 0a7370c commit 9b26727

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

Barrier.java

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
1+
import java.util.Set;
2+
import java.util.Collections;
3+
import java.util.concurrent.ConcurrentHashMap;
4+
15
public class Barrier {
26
private final int numThreads;
3-
private int waitingThreads;
7+
private Set<Long> waitingThreadIds;
48

59
public Barrier(int numThreads) {
610
this.numThreads = numThreads;
7-
this.waitingThreads = 0;
11+
this.waitingThreadIds = Collections.newSetFromMap(
12+
new ConcurrentHashMap<Long, Boolean>()
13+
);
14+
815
}
916

1017
public void await() {
11-
// TODO: can't just rely on the count, keep a list of threads waiting.
12-
// Since the same thread may call await() more than once.
13-
waitingThreads++;
14-
while(waitingThreads < numThreads) {
15-
Thread.currentThread().yield();
18+
Thread t = Thread.currentThread();
19+
waitingThreadIds.add(t.getId());
20+
while(waitingThreadIds.size() < numThreads) {
21+
t.yield();
1622
}
1723
}
1824
}

0 commit comments

Comments
 (0)