File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes synchronized method(s) purpose Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "synchronized method(s) purpose" Watch "synchronized method(s) purpose" New topic
Author

synchronized method(s) purpose

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 422
Are there any differences in the following 3 programs in terms of locking on 1 or 2 methods or within the method.



OCPJP 6.0-81% | Preparing for OCWCD
http://www.certpal.com/blogs/cert-articles | http://sites.google.com/site/mostlyjava/scwcd |
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
Can you perhaps make your question more clear? I can't tell what you're asking.

rc
Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 422
Sure. Let me start step by step. If I say a single method is synchronized, Do we get lock on that particular method or whole class level ?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4457
    
    8

If you mark a static method synchronized, it synchronizes on the class. A thread entering one of these prevents another thread entering any other such method.

If you mark a normal method synchronized, it synchronizes on the instance. So two threads can run the method at the same time if they're called on different objects, but on the same object only one synchronized method can be called at a time.

Your method3 example is a long-hand way of doing exactly the same as marking the method synchronized. This gives you more flexibility because:
a) You can synchronize on any object you want
b) You can synchronize only part of the method body, if you want
If you don't need this flexibility, just use the short-cut of marking the method.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronized method(s) purpose