Concurrency in Java: synchronized static methods

前端 未结 6 1054
礼貌的吻别
礼貌的吻别 2020-12-09 21:05

I want to understand how locking is done on static methods in Java.

let\'s say I have the following class:

class Foo {
    private static int bar = 0         


        
6条回答
  •  旧时难觅i
    2020-12-09 21:48

    A synchronized static method is effectively equivalent to:

    public static void foo() {
        synchronized (ClassName.class) {
            // Body
        }
    }
    

    In other words, it locks on the Class object associated with the class declaring the method.

    From section 8.4.3.6 of the JLS:

    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.

提交回复
热议问题