• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

synchronized methods

 
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
there are two synchronized methods,s1 and s2 in the same class and two threads t1 and t2 in the same class.now t1 is inside method s1 and t2 wants to execute s2.Will it be able to able to execute s2.
One more thing,is there one lock per class or one lock per method for our case?
 
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Assuming something like this:

If thread T1 is executing the method m1, then thread T2 will wait when it tries to execute m2 until T1 exits m1. The lock is specific to the instance of the class, i.e. synchronized(this).
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Locks go with objects.

For non-static synchronized methods, we lock on the object instance.

For static synchronized methods, we lock on the Class object, so it acts like there is one lock for the whole class.

When we do synchronized(thing) we specify the object.

Imagine an office with only a refrigerator that must be locked to keep riffraff from stealing food. And there is only one key, which is kept on a hook. When you want your lunch, you go to the hook. If the key is there, you take it and go. If not, you wait for somebody else to bring it back.

If I have two offices on neighboring floors that share a refrigerator and a key, that sounds like a static variable. One key for the "class" office. If we have two offices and each has its own refrigerator, that sounds like a member variable, one key per office instance.

Analogies like this always break down at some point. Was it helpful at all? See if it holds up when you get to studying wait, notify and so on.
 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks a lot for your nice explanation
 
reply
    Bookmark Topic Watch Topic
  • New Topic