LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 12

compareAndSet with expected values Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.concurrent.atomic.AtomicReference;

public class Main {
    public static void main(String[] args) {
        AtomicReference<String> status = new AtomicReference<>("NEW");
        boolean a = status.compareAndSet("NEW", "PAID");
        boolean b = status.compareAndSet("NEW", "CANCELLED");     // fails: it is no longer NEW
        String c = status.getAndSet("SHIPPED");
        String d = status.updateAndGet(s -> s + "!");
        System.out.println(a + " " + b + " " + c + " " + d);
    }
}
  • A true false PAID SHIPPED! Correct
  • B true true CANCELLED SHIPPED!
  • C false false NEW SHIPPED!
  • D true false SHIPPED SHIPPED!
Correct Answer: Option A

compareAndSet succeeds only when the current value matches the expected one – a lock-free state transition. (String literals are interned, so the identity check works here.)

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