*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes thread question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "thread question" Watch "thread question" New topic
Author

thread question

Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
hi ,I got it from
http://technoheads.blogspot.com

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 accesible 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? Options Select 1 correct option
(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 : 2
Explanation : (1) This may result in a deadlock (3) The is not necessary. Option 2 works just fine.

can anyone explain why the first option would end up in deadlock?

Preparing Scjp1.5
M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137


Option 1 may result in deadlock because if the second thread is calling getLocks(obj2,obj1) and the first thread is calling getLocks(obj1,obj2)in the following order, deadlock will occur!

thread1 gets the chance to execute and acquires lock on obj1 and assume that immediately thread scheduler has given thread2 priority to run! thread1 will be holding the lock on obj1.
thread2 will start executing and acquires lock on obj2 and then tries to lock object obj1 but its already held by thread1. So it will start waiting for obj1 to be available! And thread2 will be holding the lock on obj2.
after that thread1 gets the chance to execute and tries to lock object obj2
which is held by thread2. it will start waiting for obj2's lock.

Both threads will be waiting for the locks held by each other and they will be keep on waiting...
Hence the deadlock!

Hope you will get it!


Thanks,<br />Srilatha M
Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Thanks Srilatha. I am clear now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread question
 
Similar Threads
synchronized
Thread Doubt
Threads,locks problem
Synchronization
Synchronized