“class-level locking” and object-level locking are artificial ideas created by authors who probably don’t have a deep understanding of how Java built-in locking works.
class-level locking is as follows:
class Foobar { static synchronized void moo() { ... } }
But this construct is actually just a shorthand way of writing:
class Foobar { static void moo() { synchronized (Foobar.class) { ... } } }
And an object level lock that looks like this:
class Foobar { synchronized void baa() { ... } }
There is nothing short of abbreviation:
class Foobar { static void baa() { synchronized (this) { ... } } }
So, under the "class level lock" and "object level" there is only one concept: the synchronized block:
synchronized(objectReference) {...}
All you need to know is that the JVM does not allow you to synchronize more than one thread on the same object at the same time.
When the data you want to protect is global, then it makes sense to synchronize the global singleton object when accessing the data. Foobar.class - global singleton.
When the data you want to protect is completely contained in any instance of the object, then it makes sense to synchronize something related to this instance, or, in the instance itself (i.e. this ).
james large
source share