Satish Pandey
Satish Pandey

Reputation: 1184

Is it true that synchronized blocks in java acquire the whole object lock?

I know how synchronized methods in java work.

Suppose we have 3 synchronized methods in a class. If a Thread accesses 1 of the available methods, the other 2 get blocked for other threads.

If we change the synchronization implementation in 1 of methods to :

synchronized (this) {...}

Does it still work the same way and block the 2 other methods?

Upvotes: 0

Views: 368

Answers (3)

Keppil
Keppil

Reputation: 46219

This is explained in the Java Tutorials section Intrinsic Locks and Synchronization (emphasis mine):

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

So, the answer is yes.

Upvotes: 2

assylias
assylias

Reputation: 328737

Yes it does.

public synchronized void method() {...}

uses the object's instrinsic lock (this), so any other synchronized block using that lock:

synchronized(this) {...}

would block if the lock is already held.

Note: if a method is static, the picture is different, because the lock is not this any more, it is YourObject.class. In the example below, nothing prevents a thread T1 to run method while another thread T2 runs someOtherMethod, because the 2 sections don't use the same lock:

public static synchronized void method() {...}

public void someOtherMethod() {
    synchronized(this) {
    }
}

Upvotes: 1

SLaks
SLaks

Reputation: 887767

Yes.

The synchronized keyword, when applied to a method, is equivalent to wrapping the contents of the method in synchronized(this).

The spec says:

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

Upvotes: 1

Related Questions