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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
jbu
  • 15,831
  • 29
  • 82
  • 105

8 Answers8

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.

ronak
  • 49
  • 11
Cowan
  • 37,227
  • 11
  • 66
  • 65
132

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

Yes. :)

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 82
    Please answer Elaborate so that everyone can understand. – Madhu Sep 02 '09 at 04: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 '12 at 23:36
  • This answer is wrong -`this` is the lock acquired on instance methods-, please fix it Oscar. – deprecated Oct 31 '12 at 15:10
  • 1
    @vemv The question is regarding class methods, not instance methods. – OscarRyz Oct 31 '12 at 15:16
  • Note that you don't include this context in your question - and neither it is on the question's title. – deprecated Oct 31 '12 at 16:12
  • 23
    @vemv Well yes, to understand the answer you have to read the question first. – OscarRyz Oct 31 '12 at 17:27
  • @vemv There is no `this` in a static method, Please read the question. – user207421 Nov 20 '15 at 09:55
  • Which is better ?Making the static methods synchronized or using a synchronized block with a static object lock inside such methods, or are they same? – bitsabhi Feb 18 '16 at 12:20
  • Added "Since a static method has no associated object," to the answer. Otherwise "YES" for the query of "will the synchronized keyword lock on the class, instead of the object?" is misleading in absence of above context. – Ravindra babu Nov 01 '16 at 08:07
  • what if the class object is an abstract class @OscarRyz – vash_ace Aug 04 '17 at 05:01
  • @vash_ace The class itself. When you inherit from that class now the child class is the class. https://gist.github.com/oscarryz/263171aff2064c3162ebfb79faaf499c – OscarRyz Mar 01 '19 at 21:42
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.

jfpoilpret
  • 10,449
  • 2
  • 28
  • 32
  • 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 09 '11 at 03:36
  • 23
    Yes, your non-static method must explicitly synchronize on the class itself (ie, `synchronized (MyClass.class) {...}`. – jfpoilpret Dec 09 '11 at 05:57
  • @jfpoilpret "synchronized (MyClass.class) {...}" is equivalent to make this method static synchronized, right? – crazymind Feb 16 '19 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).

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
  • 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 '10 at 06: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.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
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
    
Ravi
  • 30,829
  • 42
  • 119
  • 173
0

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.

Pragya
  • 1