Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Synchronization

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi

Can anyone explain me the output of the following code

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 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.
 
Bartender
Posts: 1638
IntelliJ IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic