3

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.

Basixp
  • 115
  • 6

2 Answers2

2

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.

Community
  • 1
  • 1
Andreas Wederbrand
  • 38,065
  • 11
  • 68
  • 78
  • But it seems that every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions; so if we dealing with some kind of polymorphic behavior, are we always getting different Class? meaning the Class is never shared? – Basixp Jul 08 '13 at 19:19
  • @Basixp Your question is confusing. Arrays don't have static methods, and static methods aren't polymorphic. What are you trying to do? – Paul Bellora Jul 08 '13 at 19:25
  • meaning within a polymorphic object hierarchy, lets say we have Base and then Derived1, Derived2, etc, where derived objects introduce static synchronized methods; is everybody using same Class? – Basixp Jul 08 '13 at 19:35
  • Static methods more-or-less ignore type hierarchies. Static synchronized methods on `Base` synchronize on `Base.class`; static synchronized methods on `Derived1` synchronize on `Derived1.class`. – Louis Wasserman Jul 08 '13 at 19:39
  • @Basixp One property of static methods is that classes cannot override them. So if Base has `static void foo` and Derived1 has `static void foo` while Derived2 does not, when invoking `Dervied1.foo()` the Derived class will block which with `Derived2.foo()` the Base class will block. – John Vint Jul 08 '13 at 19:41
1

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.

John Vint
  • 39,695
  • 7
  • 78
  • 108