Java synchronized static methods: lock on object or class

JavaClassStaticMethodsSynchronized

Java Problem Overview


The Java documentation says:

> It is not possible for two invocations of synchronized methods on the > same object to interleave.

What does this mean for a static method? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?

Java Solutions


Solution 1 - Java

Just to add a little detail to Oscar's (pleasingly succinct!) answer, the relevant section on the Java Language Specification is 8.4.3.6, 'synchronized Methods':

> 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.

Solution 2 - Java

> Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?

Yes. :)

Solution 3 - Java

One point you have to be careful about (several programmers generally fall in that trap) is that there is no link between synchronized static methods and sync'ed non static methods, ie:

class A {
    static synchronized f() {...}
    synchronized g() {...}
}

Main:

A a = new A();

Thread 1:

A.f();

Thread 2:

a.g();

f() and g() are not synchronized with each other and thus can execute totally concurrently.

Solution 4 - Java

Unless you implement g() as follows:

g() {
    synchronized(getClass()) {
        ...
    }
}

I find this pattern useful also when I want to implement mutual exclusion between different instances of the object (which is needed when accesing an external resource, for example).

Solution 5 - Java

Have a look at oracle documentation page on Intrinsic Locks and Synchronization

> You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

Solution 6 - Java

A static method also has an associated object. It belongs to Class.class file in JDK toolkit. When the .class file load into the ram, the Class.class creates a instance of it called template object.

Eg :- when you try to create object from existing customer class like

Customer c = new Customer();

The Customer.class load into RAM. In that moment Class.class in JDK toolkit creates an Object called Template object and load that Customer.class into that template object.Static members of that Customer.class become attributes and methods in that template object.

So a static method or attribute also has an object

Solution 7 - Java

Below examples gives more clarity between class and object lock, hope below example will help others as well :)

For example we have below methods one acquire class and other acquire object lock :

public class MultiThread {

    public static synchronized void staticLock() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }

    public synchronized void objLock() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
}

So, now we can have following scenarios :

  1. When threads using same Object tries to access objLock OR staticLock method same time (i.e. both threads are trying to access same method)

    Thread-0 0
    Thread-0 1
    Thread-0 2
    Thread-0 3
    Thread-0 4
    Thread-1 0
    Thread-1 1
    Thread-1 2
    Thread-1 3
    Thread-1 4
    
  2. When threads using same Object tries to access staticLock and objLock methods same time (tries accessing different methods)

    Thread-0 0
    Thread-1 0
    Thread-0 1
    Thread-1 1
    Thread-0 2
    Thread-1 2
    Thread-1 3
    Thread-0 3
    Thread-0 4
    Thread-1 4
    
  3. When threads using different Object tries to access staticLock method

    Thread-0 0
    Thread-0 1
    Thread-0 2
    Thread-0 3
    Thread-0 4
    Thread-1 0
    Thread-1 1
    Thread-1 2
    Thread-1 3
    Thread-1 4
    
  4. When threads using different Object tries to access objLock method

    Thread-0 0
    Thread-1 0
    Thread-0 1
    Thread-1 1
    Thread-0 2
    Thread-1 2
    Thread-1 3
    Thread-0 3
    Thread-0 4
    Thread-1 4
    

Solution 8 - Java

For those who are not familiar static synchronized method locked on class object e.g. for string class its String.class while instance synchronized method locks on current instance of Object denoted by “this” keyword in Java. Since both of these object are different they have different lock so while one thread is executing static synchronized method , other thread in java doesn’t need to wait for that thread to return instead it will acquire separate lock denoted byte .class literal and enter into static synchronized method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjbuView Question on Stackoverflow
Solution 1 - JavaCowanView Answer on Stackoverflow
Solution 2 - JavaOscarRyzView Answer on Stackoverflow
Solution 3 - JavajfpoilpretView Answer on Stackoverflow
Solution 4 - Javauser267405View Answer on Stackoverflow
Solution 5 - JavaRavindra babuView Answer on Stackoverflow
Solution 6 - JavaPahansith GunathilakeView Answer on Stackoverflow
Solution 7 - JavaRaviView Answer on Stackoverflow
Solution 8 - JavaPragyaView Answer on Stackoverflow