PENNY
PENNY

Reputation: 91

Synchronized methods and locks

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 but what happens when a static synchronized method is invoked because a static method is associated with a class not an object?

Upvotes: 1

Views: 133

Answers (3)

MarsaPalas
MarsaPalas

Reputation: 415

Just to make it clear- that still means, for example, one thread executes a synchronized nonstatic method, while the other does synchronized static method. You just cannot have two threads execute 2 synchronized static methods at the same time.

Upvotes: 1

M S
M S

Reputation: 4093

Every classes and interface in java has an associated object.

For a class name MyClass, you can get the class object by

MyClass.class

From any object obj, you can get the class object by

obj.getClass()

The lock is obtained for this object when a static method is synchronized.

Upvotes: 3

socha23
socha23

Reputation: 10239

A class is an Object too. When invoking synchronized static method, you acquire a lock on Class object.

Upvotes: 5

Related Questions