#497 CountDownLatch and Lost Increments
Will CountDownLatch count down the required number of times?
public class Increment {
private static int counter1 = 0;
private static int counter2 = 0;
Lock lock = new ReentranLock();
public static void main(String[] args) throws InterruptedException {
int exercisesCount = 100_000;
CountDownLatch latch = new CountDownLatch(exercisesCount);
ExecutorService executor = Executors.newFixedThreadPool(100);
for (int i = 0; i < exercisesCount; i++) {
executor.submit(() -> {
counter1++;
counter2++;
latch.countDown();
});
}
latch.await();
// how much will be printed?
System.out.println(counter1);
System.out.println(counter2);
System.exit(0);
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor