QuestionQ27

Concurrency

Given the following code fragments:

Question Image

and

Question Image

Which statement is correct?

  • A The program prints t1 : 1 : t2 : 1: t1 : 2 : t2 : 2 : in random order.
  • B The program prints t1 : 1 : t2 : 1: t1 : 2 : t2 : 2 :
  • C The program prints t1 : 1 : t2 : 1: t1 : 1 : t2 : 1 : indefinitely.
  • D The program prints an exception.
Explanation

The volatile x is read and incremented only by t1, so t1 outputs 1 and 2. AtomicInteger.get() reads the current value and getAndIncrement() atomically increments it, so t2 outputs 1 and 2 before its loop terminates at 3. Because the threads run concurrently, their output calls may interleave in a scheduling-dependent order. Oracle documents that AtomicInteger.get() reads the current value and that getAndIncrement() atomically increments it.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!