Implementing a Barrier
This lesson discusses how a barrier can be implemented in Java.
We'll cover the following...
Problem Statment
A barrier can be thought of as a point in the program code, which all or some of the threads need to reach at before any one of them is allowed to proceed further.
Solution
A barrier allows multiple threads to congregate at a point in code before any one of the threads is allowed to move forward. Java and most other languages provide libraries which make barrier construct available for developer use. Even though we are re-inventing the wheel but this makes for a good interview question.
We can immediately realize that our solution will need a count variable to track the number of threads that have arrived at the barrier. If we have n threads, then n-1 threads must wait for the nth thread to arrive. This suggests we have the n-1 threads execute the wait method and the nth thread wakes up all the asleep n-1 threads. Below is the code:
1. public class Barrier {
2.
3. int count = 0;
4. int totalThreads;
5.
6. public Barrier(int totalThreads) {
7. this.totalThreads = totalThreads;
8. }
9.
10. public synchronized void await() throws InterruptedException {
11. // increment the counter whenever a thread arrives at the
12. // barrier.
13. count++;
14.
15. if (count == totalThreads) {
16. // wake up all the threads.
17. notifyAll();
18. // remember to reset count so that barrier can be reused
19. count =
...