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