Question 12
Back to Exercise
What is the output of the following Java program?
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!