Threading Model   «Prev 


Synchronized Methods to avoid Deadlock

The importance of synchronization
The importance of synchronization

Arrow from thread A to object Thread A starts object update.
Arrow from object partially updated to thread B Thread B accesses object while in half-updated state. The object returns junk.
Arrow from object partially updated to updated object Thread B accesses object while in half-updated state. The object returns junk.

The following quiz question is with regards to how one should avoid a deadlock when using the synchronized keyword.

Synchronized methods to avoid a deadlock:

Consider the following method:
public void getLocks(Object a, Object b){
  synchronized(a){
    synchronized(b){
      //do something
    }
  }
}

and the following instantiations:
Object obj1 = new Object();
Object obj2 = new Object();

obj1 and obj2 are accessible to two different threads and the threads are about to call the getLocks() method.
Assume the first thread calls the method getLocks(obj1, obj2).
Which of the following options avoids a deadlock?
  1. The second thread should call getLocks(obj2, obj1)
  2. The second thread should call getLocks(obj1, obj2)
  3. The second thread should call getLocks() only after first thread exits out of it.
  4. The second thread may call getLocks() any time and passing parameters in any order.
  5. None of the above.


Answer: b
Explanation: a. This may result in a deadlock.
c. This is not necessary and option 2 works correctly.
d. It should not call getLocks(obj2, obj1) because it may result in a deadlock.