Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized methods  RSS feed

 
Raj Kumar Bindal
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • 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?
 
Chris Beckey
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • 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).
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
thanks a lot for your nice explanation
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!