Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static synchronized and non static synchronized methods in threads

can any one explain the statement ..."static synchronized method and non static synchronized method will not block each other -they can run at the same time"

like image 402
satheesh Avatar asked Apr 13 '11 19:04

satheesh


Video Answer


2 Answers

static synchronized void test() { foo(); }

equals

static void test() { synchronized(MyClass.class) { foo(); } }

while

synchronized void test() { foo(); }

equals

void test() { synchronized(this) { foo(); } }

This means: static methods lock on the class object of the class. Non-static methods lock on the instance on which they're called (by default, synchronized(anyOtherLock) is also possible). Since they lock on different objects, they don't block each other.

like image 186
atamanroman Avatar answered Oct 04 '22 21:10

atamanroman


The lock objects are different on the static method and non-static method. The static method uses the Class object as the lock (lock obj: MyClass.class), while the non-static method uses the instance object as the lock to which the invocation of the method at that time is bound (lock obj: this).

like image 37
Chris Dennett Avatar answered Oct 04 '22 22:10

Chris Dennett