Concurrency in Java: synchronized static methods

前端 未结 6 1042
礼貌的吻别
礼貌的吻别 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:56

    Static locks are attached to the class definition and thus is shared between all instances of that class.

    Synchronization of none static methods only apply to the current instance of the class (the lock is on the class instance, e.g., this). In your example you have two different locks with no interrelation.

    I don't want two threads to simultaneously call both f.get() and Foo.inc(), but these methods acquire different locks. My question is how is this preventable and is it prevented in the above code

    You must share a lock to be able to arbitrate access to both f.get and Foo.inc(). You can do this either by sharing the same static lock or by the same instance lock.

提交回复
热议问题