LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 11

An AtomicInteger shared by pool tasks Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links