java static synchronized method

浪子不回头ぞ 提交于 2019-12-21 20:18:54

问题


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?


回答1:


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



回答2:


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:


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.




回答4:


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



来源:https://stackoverflow.com/questions/12492553/java-static-synchronized-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!