java static synchronized method

2019-04-12 12:05发布

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?

4条回答
可以哭但决不认输i
2楼-- · 2019-04-12 12:19

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.

查看更多
做个烂人
3楼-- · 2019-04-12 12:37

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
        }
    }
}
查看更多
Emotional °昔
4楼-- · 2019-04-12 12:39

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.

查看更多
We Are One
5楼-- · 2019-04-12 12:41

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

查看更多
登录 后发表回答