Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

lock for instance method and class static method

 
Edward Chen
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As we know, we can use synchronized to instance method and class static method. Synchronized means one thread has to hold lock (monitor). Then in the both synchronized method (static and instance), the lock (monitor) is same ?

thanks.
 
Vijitha Kumara
Bartender
Pie
Posts: 3918
10
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Edward Chen wrote:As we know, we can use synchronized to instance method and class static method. Synchronized means one thread has to hold lock (monitor). Then in the both synchronized method (static and instance), the lock (monitor) is same ?

No. There are two locks namely "class lock" & "instance lock". "class lock" is associated with the Class object of that class and the instance lock is associated with the object itself. So you get instance lock for each instance you create. Static blocks synchronize on "class lock" while instance lock synchronizes on instance (object) lock.
 
Mohammed Yousuff
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


in above code synchronized block was done in Class Level and the entire class was LOCKED.




In the above code only the object was get locked not the class....


 
Vijitha Kumara
Bartender
Pie
Posts: 3918
10
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohammed Yousuff wrote:
in above code synchronized block was done in Class Level and the entire class was LOCKED.

I don't know what you mean by "entire class was LOCKED.. " but you still able to invoke any other instance methods (if any) of a given instance of that class.And the reverse is also true for instance locks, that is you are still able to invoke static/non-synchronized instance methods in case of instance lock.
 
Mohammed Yousuff
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vijitha Kumara ...You are right...

"entire class was LOCKED.. " I just mean that all static method in the Class will get LOCKED...

i think we both are Sailing in the same boat

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic