Is a synchronized block equivalent to a static synchronized method?

If you have a method like:

public synchronized void addOne() { a++; } 

this is equivalent to the following: (correct me if I am wrong)

 public void addOne() { synchronized(this) { a++; } } 

But what is equivalent to the following method ?:

 public static synchronized void addOne() { a++; // (in this case 'a' must be static) } 

What is a synchronized block that acts just like a static synchronized method? I understand that a static synchronized method is synchronized with the class, not the instance (since there is no instance), but what is the syntax for this?

+4
source share
1 answer

This is equivalent to locking a class object. You can get a reference to a class object by writing the class name followed by .class . So something like:

 synchronized(YourClass.class) { } 

See Java Language Specification, Section 8.4.3.6 synchronized Methods :

A synchronized method receives a lock (ยง17.1) before it is executed. For a class (static) method, the lock associated with the class object is used for the method class. For the instance method associated with locking with this (the object for which the method was called).

+10
source

All Articles