9

When you have a method such as the following:

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

it is equivalent to the following: (correct me if I'm wrong)

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

But what is the 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 the same as a static synchronized method? I understand the static synchronized method is synchronized on the class and not the instance (since there is no instance), but what is the syntax for that?

Ricket
  • 33,368
  • 30
  • 112
  • 143
  • possible duplicate of [Java synchronized methods: lock on object or class](http://stackoverflow.com/questions/437620/java-synchronized-methods-lock-on-object-or-class) – Pascal Thivent Jul 25 '10 at 04:04
  • Eh, but that question doesn't have the code snippet that Quartermeister pointed out. I think this is distinct and good to have on hand. – Ricket Jul 26 '10 at 02:12

1 Answers1

23

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

synchronized(YourClass.class) {
}

See the Java Language Specification, Section 8.4.3.6 synchronized Methods:

A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method, the lock associated with the Class object for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.

Quartermeister
  • 57,579
  • 7
  • 124
  • 111
  • Yes, and thanks for referencing the JLS - always an interesting read! Here is an updated link on the Oracle domain: [JLS §8.4.3.6](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.3.6). It also provides a trivial example which illustrates that "the monitor associated with the Class object" is indeed the class itself. – typeracer Aug 09 '19 at 08:25