views:

62

answers:

3

Hi,

I have 2 synchronized methods in a class say method1() and method2(). A thread say "Thread 1" holds the lock on that object of the class by executing the synchronized method1().Can another thread say "Thread 2" , access the lock via method2() at the same time while "Thread 1" holding the lock.

This case is analogs to java.util.Vector class having synchronized add() and remove() methods. Please explain this case too.

+3  A: 

No. A synchronized method in Java is identical to the whole method having its body wrapped in a synchronized (this) block. So if one thread is in a synchronized method, another thread cannot simultaneously be in a different synchronized method on the same object.

The way this relates to a Vector is that you don't want some code trying to remove an element while other code is trying to add an element. This is the concept of a critical section; you not only don't want someone else trying to do what you're doing, you also don't want someone else doing something different that would interfere.

Borealid
Thanks Borealid..But if this is the case,Why java provides synchronization specific to methods,it can just provided for the whole class?
JavaUser
@JavaUser: `synchronized (this)` does not mean the whole class is `synchronized`. It means you acquire the Object lock of the instance on which the method was called. You don't necessarily want *all* of the methods to be `synchronized` (in fact, you rarely ever will). To get the performance of multithreaded code you must use as few locks as possible while preserving program correctness - each time you have a contended lock, some thread will wait, doing nothing.
Borealid
@Borealid..the moment I defined synchronized in any method means,the whole object is locked when I call that method ..am I right?
JavaUser
@JavaUser: not exactly. If you have a synchronized method, that means that when it's called no other synchronized method can run until it's finished. The object *has its lock acquired*, but that doesn't mean other methods (which are not synchronized) cannot run.
Borealid
Thanks Borealid ..Now its clear
JavaUser
A: 

Thread2 can access the lock but can't enter the block guarded by that lock as long as Thread1 is holding the same lock.

Willi
A: 

No, only one thread can hold the lock at one time

http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/essential/concurrency/syncmeth.html

objects