#240 Lost Increments in Multithreaded Code
What will be printed?
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Increment {
private static int counter1 = 0;
private static int counter2 = 0;
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();
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