1Z0-809 · Question #229
Given the code fragment: ``java final List<String> list = new CopyOnWriteArrayList<>(); final AtomicInteger ai = new AtomicInteger(0); final CyclicBarrier barrier = new CyclicBarrier(2, new…
The correct answer is A. [X, X]. Option A is correct because the CyclicBarrier is configured with 2 parties, meaning its action fires every time exactly 2 threads call await(). With four threads sleeping for 1, 2, 3, and 4 seconds respectively, the first two threads each add "X" to the list before calling…
Question
final List<String> list = new CopyOnWriteArrayList<>();
final AtomicInteger ai = new AtomicInteger(0);
final CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {
public void run() { System.out.print(list); }
});
Runnable r = new Runnable() {
public void run() {
try {
Thread.sleep(1000 * ai.incrementAndGet());
list.add("X");
barrier.await();
} catch (Exception ex) { }
}
};
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
What is the result?Options
- A[X, X]
- B[X, X, X]
- C[X]
- D[X, X, X, X]
How the community answered
(67 responses)- A76% (51)
- B3% (2)
- C7% (5)
- D13% (9)
Explanation
Option A is correct because the CyclicBarrier is configured with 2 parties, meaning its action fires every time exactly 2 threads call await(). With four threads sleeping for 1, 2, 3, and 4 seconds respectively, the first two threads each add "X" to the list before calling await(), triggering the barrier action which prints [X, X]. Option C ([X]) is impossible because 2 threads must reach the barrier before it trips, guaranteeing at least 2 elements in the list; similarly, B ([X, X, X]) would require parties=3, but the barrier here only needs 2 - it never waits for a third. Option D ([X, X, X, X]) is what gets printed when the barrier fires a second time (threads 3 and 4 arrive later and form a new cycle), not the first observable result. Memory tip: "Parties value = X count per print" - whatever number you pass to CyclicBarrier(n, ...), that's exactly how many threads add their element before each barrier action fires.
Community Discussion
No community discussion yet for this question.