#240 Lost Increments in Multithreaded Code

Companies:
T-Bank
Themes:
JavaConcurrencyCode Review

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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in