java static synchronized method
Asked Answered
B

4

3

What happens when a static synchronized method is called by two threads using different instances at the same time? Is it possible? The object lock is used for non static synchronized method but what type lock is used for static synchronized method?

Bunkum answered 19/9, 2012 at 10:6 Comment(2)
static methods ignore the instance variable if provided. It can even be null without error. For static methods the class object is used.Lick
Discussed in #438120Cultivate
T
6

It is the same as synchronizing on the Class object implementing the method, so yes, it is possible, and yes, the mechanism effectively ignores the instance fro which the method is called:

class Foo {
    private static synchronized doSomething() {
        // Synchronized code
    }
}

is a shortcut for writing this:

class Foo {
    private static doSomething() {
        synchronized(Foo.class) {
            // Synchronized code
        }
    }
}
Tourist answered 19/9, 2012 at 10:10 Comment(0)
C
6

It is possible.

The threads lock on the Class object of the class, like on MyClass.class.

See JLS, Section 8.4.3.6. synchronized Methods:

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.

Cultivate answered 19/9, 2012 at 10:10 Comment(0)
C
0

static synchronized methods use locks on instance of type java.lang.Class. That is, each accessible class is represented by an object of type Class in runtime, and that object is used by static synchronized methods.

Canaster answered 19/9, 2012 at 10:11 Comment(0)
S
0

When using a static lock the objects are ignored. The lock is acquired on class rather than objects.

Schultz answered 20/8, 2017 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.