File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes lock for instance method and class static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "lock for instance method and class static method" Watch "lock for instance method and class static method" New topic
Author

lock for instance method and class static method

Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798
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

Joined: Mar 24, 2008
Posts: 3859

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.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198


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....



My Thoughts : http://passion4java.blogspot.com
Try not to become a man of success but rather to become a man of value.
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3859

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

Joined: Oct 17, 2007
Posts: 198
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

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: lock for instance method and class static method