Question 11
Back to Exercise
What is the output of the following Java program?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger visits = new AtomicInteger();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 1000; i++) pool.submit(visits::incrementAndGet);
}
System.out.println(visits.get() + " " + visits.addAndGet(-500) + " " + visits.getAndIncrement() + " " + visits);
}
}
- A 1000 500 500 501 Correct
- B 1000 500 501 501
- C less than 1000 500 500 501
- D 1000 -500 500 501
Correct Answer: Option A
Atomic increments never lose updates. getAndIncrement returns the old value (500) and then adds 1.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!