views:

168

answers:

5

What is the difference between synchronized methods and synchronized statements ?

If possible , please use an example to make it more clear.

Thanks.

A: 

synchronized method is a lock on a this object. it's equals to synchronized (this) {}

synchronized is a locking on he some object/monitor. With synchronized (***) {} you can choose an object you are locking on. With synchronized method current object instance will be a locking monitor.

splix
+1  A: 

A synchronized method is a method whose body is encapsulated automatically in a synchronized block.

Thus, this is equal:

public void foo()
{
    synchronized (this)
    {
        bar();
    }
}

public synchronized void foo()
{
    bar();
}
PartlyCloudy
+3  A: 
polygenelubricants
A: 

A synchronized method is one where you have, in effect, placed the entire body of the function in a synchronized block. A synchronized block has the advantage that you can apply the synchronized block to just a few select statements in the function, instead of to the function as a whole. In general, it is best to make synchronized blocks as short as possible, since time spent in synchronized blocks is time that some other thread might be prevented from doing meaningful work. Another distinction is that you can specify a particular object on which to apply the lock when using a synchronized block whereas with a synchronized method, the object, itself is automatically used as the lock on which synchronization is performed.

Michael Aaron Safyan
+5  A: 

A synchronized method locks the monitor associated with the instance of the class (ie 'this') or the class (if a static method) and prevents others from doing so until the return from the method. A synchronized block can lock any monitor (you tell it which) and can have a scope smaller than that of the encolsing method.

Synchronized blocks are prefered if they don't end up equivalent to the entire scope of the method and/or if they lock something less draconian than the instance (or class if static).

RayAllen