Concurrency in Java: synchronized static methods

前端 未结 6 1046
礼貌的吻别
礼貌的吻别 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条回答
  •  庸人自扰
    2020-12-09 21:46

    Neither, the non-static synchronized call does not acquire a lock on the class itself. (And the static synchronized block does not lock any object instantiated from that class.)

    In other words the calls f.get() (locks f) and Foo.inc() (locks the class Foo) can run concurrently. They are not "synchronized".

    You could use a different pattern (singleton), or make all the methods static.

提交回复
热议问题