Question 14
Back to Exercise
What is the output of the following Java program?
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch done = new CountDownLatch(4);
AtomicInteger checked = new AtomicInteger();
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) pool.submit(() -> { checked.addAndGet(25); done.countDown(); });
done.await(); // returns when the count reaches 0
System.out.println(checked.get() + "% " + done.getCount());
done.countDown(); // no effect once at zero
System.out.println(done.getCount());
pool.shutdown();
}
}
- A 100% 0 0 Correct
- B 100% 0 -1
- C 75% 1 0
- D It varies
Correct Answer: Option A
await returns once all four tasks have counted down; a latch never goes below zero and cannot be reset.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!