150

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?

0

8 Answers 8

203

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.

1
  • 17
    Useful, I was looking for that quote +1
    – OscarRyz
    Jan 13, 2009 at 3:06
131

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

Yes. :)

9
  • 83
    Please answer Elaborate so that everyone can understand.
    – Madhu
    Sep 2, 2009 at 4:49
  • 6
    @Madhu. It means that if you have 2 or more synchronized methods on the same class, both cannot execute at the same time, even when there are multiple instances of that class. The locking is essentially the same as locking on the Object.class for each synchronized method.
    – Steven
    Oct 16, 2012 at 23:36
  • This answer is wrong -this is the lock acquired on instance methods-, please fix it Oscar.
    – deprecated
    Oct 31, 2012 at 15:10
  • 1
    @vemv The question is regarding class methods, not instance methods.
    – OscarRyz
    Oct 31, 2012 at 15:16
  • 23
    @vemv Well yes, to understand the answer you have to read the question first.
    – OscarRyz
    Oct 31, 2012 at 17:27
81

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.

3
  • 18
    but what if g() is mutating some static variable which f() is reading. How do we make that thread safe? Do we explicitly acquire a lock on the class then?
    – baskin
    Dec 9, 2011 at 3:36
  • 23
    Yes, your non-static method must explicitly synchronize on the class itself (ie, synchronized (MyClass.class) {...}.
    – jfpoilpret
    Dec 9, 2011 at 5:57
  • @jfpoilpret "synchronized (MyClass.class) {...}" is equivalent to make this method static synchronized, right?
    – crazymind
    Feb 16, 2019 at 18:00
15

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

1
  • 63
    Note that there may actually be a chance of some very subtle and nasty bugs here. Remember getClass() returns the runtime type; if you subclass the class, then the parent class and the child class will synchronize on different locks. synchronized(MyClass.class) is the way to go if you need to ensure all instances use the same lock.
    – Cowan
    Nov 28, 2010 at 6:24
3

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.

2

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

2

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
    
0

For those who are not familiar static synchronized method locked on class object e.g. for string class, it's String.class while instance synchronized method locks on the current instance of Object denoted by “this” keyword in Java.

Since both of these objects are different they have a different lock so while one thread is executing the static synchronized method, the other thread in java doesn’t need to wait for that thread to return instead it will acquire a separate lock denoted byte .class literal and enter into the static synchronized method.

Source: https://javarevisited.blogspot.com/2012/03/mixing-static-and-non-static.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.