Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample69 is run - what will be the output?

import java.util.concurrent.atomic.AtomicInteger;

public class Sample69
{
    public static void main(String[] args)
    {
        AtomicInteger n = new AtomicInteger(5);
        System.out.print(n.compareAndSet(5, 9) + " ");
        System.out.print(n.compareAndSet(5, 12) + " ");
        System.out.print(n.get());
    }
}

  • A.true false 9
  • B.true true 12
  • C.false false 5
  • D.true false 12

Answer: A

The first call finds the expected 5 and writes 9, reporting success. The second still expects 5, but the value is now 9, so it writes nothing and returns false. The final value is therefore 9, and the boolean result is what lets a retry loop work without a lock.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.