MduSenthil
MduSenthil

Reputation: 2077

Can a synchronized static method cause a class level lock?

If a class A is having a public static method which is tagged by 'synchronized' keyword, then Is there a possibility to have class level lock?

When there is a lock in such class, Can We instantiate object of that class or it has nothing to do with instantiation?

Upvotes: 1

Views: 917

Answers (3)

Amir Raminfar
Amir Raminfar

Reputation: 34179

If a class A is having a public static method which is tagged by 'synchronized' keyword, then Is there a possibility to have class level lock?

Yes, there would be a class level lock on class A.

When there is a lock in such class, Can We instantiate object of that class or it has nothing to do with instantiation?

When there is a lock on a static method, it only affects other synchronized static methods. You can still create a new instance of that class.

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 692281

All the other threads trying to execute another static synchronized method of the same class, or any other method synchronized on this Class instance will be blocked.

Upvotes: 2

rajasaur
rajasaur

Reputation: 5470

Yes, the lock will be maintained on the Class object.

Quoted from Locks In Synchronized Methods

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

Upvotes: 3

Related Questions