Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized block equivalent to static synchronized method?

Tags:

java

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?

like image 536
Ricket Avatar asked Jul 25 '10 03:07

Ricket


People also ask

What is the difference between static synchronized and synchronized methods?

A synchronized block of code can only be executed by one thread at a time. Synchronization in Java is basically an implementation of monitors . When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method , the monitor belongs to the class.

Can static method be synchronized?

static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.


1 Answers

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.

like image 127
Quartermeister Avatar answered Oct 27 '22 06:10

Quartermeister