File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Synchronization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Synchronization" Watch "Synchronization" New topic


Padma Priya
Ranch Hand

Joined: Feb 01, 2007
Posts: 116

Can anyone explain me the output of the following code

Consider the following method:

public void getLocks(Object a, Object 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 is true?

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.
Nitesh Kant

Joined: Feb 25, 2007
Posts: 1638

To avoid deadlock, the second thread should call the getLocks() method with the argument in the same order.(Of course if the objects passed are the same)

Dead lock scenario(Thread2 calls getLocks(obj2, obj1)):

Lets say Thread1 has entered getLocks() and has taken the lock on obj1.(at line synchronized(a)).
At this moment, thread2 enters getLocks() and takes a lock on obj2(at line synchoronized(a) again as the parameter order has changed)

Now, when both the thread proceed, thread1 will wait for thread2 to release lock on obj2(at line synchronized(b)) and thread1 will wait for thread2 to release the lock on obj1(at line synchronized(b)). Thus, resulting in a deadlock.

apigee, a better way to API!
I agree. Here's the link:
subject: Synchronization
It's not a secret anymore!