nerdexam
Oracle

1Z0-829 · Question #1

Given the code fragments: class Test { volatile int x = 1; AtomicInteger xObj = new AtomicInteger(1); } and public static void main(String[] args) { Test t = new Test(); Runnable r1 = () -> { Thread…

The correct answer is B. The program prints t1 : 1 : t2 : 1 : t1 : 2 : t2 : 2. The code creates two threads, t1 and t2, and starts them. The threads will print their names and the value of the Atomic Integer object, x, which is initially set to 1. The threads will then increment the value of x and print their names and the new value of x. Since the…

Managing concurrent code execution

Question

Given the code fragments: class Test { volatile int x = 1; AtomicInteger xObj = new AtomicInteger(1); } and public static void main(String[] args) { Test t = new Test(); Runnable r1 = () -> { Thread trd = Thread.currentThread(); while (t.x < 3) { System.out.print(trd.getName() + ": "+t.x+" : "); t.x++; } }; Runnable r2 = () -> { Thread trd = Thread.currentThread(); while (t.xObj.get() < 3) { System.out.print(trd.getName() + ": "+t.xObj.get()+" : "); t.xObj.getAndIncrement(); } }; Thread t1 = new Thread(r1,"t1"); Thread t2 = new Thread(r2,"t2"); t1.start(); t2.start(); } Which is true?

Options

  • AThe program prints t1 : 1: t1 : 1: t1 : 2 : t2 : 2 in random order.
  • BThe program prints t1 : 1 : t2 : 1 : t1 : 2 : t2 : 2.
  • CThe program prints t1 : 1 : t1 : 1 : t2 : 1 : indefinitely
  • DThe program prints an exception

How the community answered

(31 responses)
  • A
    10% (3)
  • B
    68% (21)
  • C
    16% (5)
  • D
    6% (2)

Explanation

The code creates two threads, t1 and t2, and starts them. The threads will print their names and the value of the Atomic Integer object, x, which is initially set to 1. The threads will then increment the value of x and print their names and the new value of x. Since the threads are started at the same time, the output will be in random order. However, the final output will always be t1 : 1 : t2 : 1 : t1 : 2 : t2 : 2. Reference: AtomicInteger (Java SE 17 & JDK 17) - Oracle

Topics

#volatile keyword#AtomicInteger#thread safety#race condition

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice