Java OCA OCP Practice Question 3251

Question

Given the following code, which statements are true about the objects referenced by the fields i, j, and k, given that any thread may call the methods a(), b(), and c() at any time?.

 class Counter {/* ww w  .  ja v  a  2s.c  o  m*/
   int v = 0;
   synchronized void inc() { v++; }
   synchronized void dec() { v--; }
 }

 public class Main {
   Counter i;
   Counter j;
   Counter k;
   public synchronized void a() {
     i.inc();
     System.out.println("a");
     i.dec();
   }

   public synchronized void b() {
     i.inc(); j.inc(); k.inc();
     System.out.println("b");
     i.dec(); j.dec(); k.dec();
   }
  public void c() {
    k.inc();
    System.out.println("c");
    k.dec();
  }
}

Select the two correct answers.

  • (a) i.v is always guaranteed to be 0 or 1.
  • (b) j.v is always guaranteed to be 0 or 1.
  • (c) k.v is always guaranteed to be 0 or 1
  • (d) j.v will always be greater than or equal to k.v at any given time.
  • (e) k.v will always be greater than or equal to j.v at any given time.


(a) and (b)

Note

If a thread is executing method b() on an object, it is guaranteed that no other thread executes methods a() and b() concurrently.

Therefore, the invocation counters i and j will never show more than one concurrent invocation.

Two threads can concurrently be executing methods b() and c().

Therefore, the invocation counter k can easily show more than one concurrent invocation.




PreviousNext

Related