Concurrency basics · interview question
What's the most accurate description of what this program prints?
What does this code output?Medium
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);
}
}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.
References
Test yourself on Concurrency basics
A free test with instant, explained results. No account needed.
More Concurrency basics questions
- Which ExecutorService method stops accepting new tasks but lets already-submitted tasks finish? (method name)
- Which method is used to wait for all CompletableFutures in a list to complete?
- How can you ensure that a CompletableFuture runs on a specific Executor?
- Which situation benefits most from using AtomicInteger over synchronized blocks?
- Which CompletableFuture method should be used to execute a task asynchronously in a non-blocking manner?
- In which scenario would you use.thenCompose() over.thenApply() in CompletableFuture?