my dog learned polymorphism
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "synchronized method(s) purpose" Watch "synchronized method(s) purpose" New topic

synchronized method(s) purpose

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 423
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 | |
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.

Harikrishna Gorrepati
Ranch Hand

Joined: Sep 23, 2010
Posts: 423
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

Joined: Apr 06, 2010
Posts: 4543

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:
subject: synchronized method(s) purpose
It's not a secret anymore!