Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread intrinsic lock

When we talk about intrinsic lock we refer to the object for which we ask the lock or for the synchronized method?

The lock is on the object or on it's sync method?

I'm confused!

like image 713
xdevel2000 Avatar asked Jul 29 '10 10:07

xdevel2000


2 Answers

In Java, an intrinsic lock is implied by each use of the synchronized keyword

Each use of the synchronized keyword is associated with one of the two types of intrinsic lock:

an "instance lock", attached to a single object

a "static lock", attached to a class

If a method is declared as synchronized, then it will acquire either the instance lock or the static lock when it is invoked, according to whether it is an instance method or a static method.

The two types of lock have similar behaviour, but are completely independent of each other.

Acquiring the instance lock only blocks other threads from invoking a synchronized instance method; it does not block other threads from invoking an un-synchronized method, nor does it block them from invoking a static synchronized method.

Similarly, acquiring the static lock only blocks other threads from invoking a static synchronized method; it does not block other threads from invoking an un-synchronized method, nor does it block them from invoking a synchronized instance method.

Outside of a method header, synchronized(this) acquires the instance lock.

The static lock can be acquired outside of a method header in two ways:

synchronized(Blah.class), using the class literal

synchronized(this.getClass()), if an object is available

like image 129
Dhiral Pandya Avatar answered Oct 18 '22 01:10

Dhiral Pandya


Intrinsic locks are on the object:

class A
{
   public synchronized void method1(){...}
   public synchronized void method2(){...}
}

If thread A is in method1 then threadB cannot enter method2.

like image 21
PaulJWilliams Avatar answered Oct 18 '22 03:10

PaulJWilliams