Basixp
Basixp

Reputation: 115

Static synchronized methods

I understand that Java instance synchronized methods can run parallel and the static ones will serialize the methods; my lack of understanding is, since the static method locks the Class object, what happens with other Class objects; are we locking between all static classes?

thanks.

Upvotes: 3

Views: 159

Answers (2)

John Vint
John Vint

Reputation: 40276

Java classes have a monitor associated with the class instance. Since there is only one class instance per class the lock will only be acquired on that class instance.

Now each class defined has its own instance and thus its own monitor, so to answer your question: Synchronizing a static method will only block access to that class.

Upvotes: 1

Andreas Wederbrand
Andreas Wederbrand

Reputation: 40061

Instead of taking the lock on the instance/object you are taking it on the class it self.

When you lock the class you are only locking that class, not all classes.

From the docs

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: 2

Related Questions