Java OCA OCP Practice Question 2193

Question

Given the following program, which statement is true?

public class Main extends Thread {
  static Object lock1 = new Object();
  static Object lock2 = new Object();
  static volatile int i1, i2, j1, j2, k1, k2;
  public void run() { while (true) { doIt(); check(); } }
  void doIt() {// ww  w  . ja va2  s.  com
    synchronized(lock1) { i1++; }
    j1++;
    synchronized(lock2) { k1++; k2++; }
    j2++;
    synchronized(lock1) { i2++; }
  }
  void check() {
    if (i1 != i2) System.out.println("i");
    if (j1 != j2) System.out.println("j");
    if (k1 != k2) System.out.println("k");
  }
  public static void main(String[] args) {
    new Main().start();
    new Main().start();
  }
 }

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) One cannot be certain whether any of the letters i, j, and k will be printed during execution.
  • (c) One can be certain that none of the letters i, j, and k will ever be printed during execution.
  • (d) One can be certain that the letters i and k will never be printed during execution.
  • (e) One can be certain that the letter k will never be printed during execution.


(b)

Note

One cannot be certain whether any of the letters i, j, and k will be printed during execution.

For each invocation of the doIt() method, each variable pair is incremented and their values are always equal when the method returns.

The only way a letter could be printed would be if the method check() was executed between the time the first and the second variable were incremented.

Since the check() method does not depend on owning any lock, it can be executed at any time, and the method doIt() cannot protect the atomic nature of its operations by acquiring locks.




PreviousNext

Related