LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 14

Waiting for workers with a CountDownLatch Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links