Java OCA OCP Practice Question 1312

Question

Given the following class:

class MyClass { //  w  w  w .  j a v a  2  s .c o m
     synchronized void notStaticMethod() { 
       for (long n=0; n<100000000000L; n++) 
         System.out.println(n); 
     } 

     synchronized static void staticMethod() { 
       for (long n=0; n<100000000000L; n++) 
         System.out.println(n); 
     } 
} 

Suppose thread A and thread B both have references to each of two instances of MyClass.

These references are named myClass1 and myClass2.

Which statements are true?

Choose all correct options.

  • A. If thread A is executing myClass1.staticMethod(), then thread B may not execute myClass1.staticMethod().
  • B. If thread A is executing myClass1.staticMethod(), then thread B may not execute myClass2.staticMethod().
  • C. If thread A is executing myClass1.notStaticMethod(), then thread B may not execute myClass1.staticMethod().
  • D. If thread A is executing myClass1.notStaticMethod(), then thread B may not execute myClass1.notStaticMethod().
  • E. If thread A is executing myClass1.notStaticMethod(), then thread B may not execute myClass2.notStaticMethod().


A, B, D.

Note

There are three locks to consider:

  • the class lock, which controls access to the static synchronized method, and
  • the individual object locks, which control access to the non-static synchronized methods.

A and B are true because staticMethod() is controlled by the class lock.

C is false because myClass1.notStaticMethod() is controlled by myClass1's object lock, while myClass1.staticMethod() is controlled by the class lock.

D is true because both threads are trying to execute code controlled by myClass1's object lock.

E is false because thread A is executing code controlled by myClass1's object lock, while thread B wants to execute code controlled by myClass2's object lock.




PreviousNext

Related