Skip to content
Sharp

Concurrency basics · interview question

What's the most accurate description of what this program prints?

What does this code output?Medium
java
public class Main {
    static int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 10_000; i++) counter++;
        };
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println(counter);
    }
}
Choose one answer
Answer and explanation

Correct answer

A. A value up to 20000. It's often less, and it can change from run to run.

Why

counter++ is a read-modify-write. Two threads can read the same value and both write back value + 1, losing an increment. This is a race condition.

Test yourself on Concurrency basics

A free test with instant, explained results. No account needed.

Start free test
All Concurrency basics questions →