Question

I was going through this link . According to this :

Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object.

But according to java spec , all objects of same type(class) on heap share single Class object. So how can this be true for multi-thread synchronized access to Objects?

Was it helpful?

Solution

A class lock

synchronized (String.class) {...}

An object lock

//doesn't matter what the lock object is as long as it's not null
private final Object lock = new Object(); 
...
synchronized (lock) {...} // will throw NPE if lock is null

They're both considered object locks because String.class returns an instance of Class<String>.

In the class lock, the thread acquires the Class<String> instance monitor. In the object lock, the thread acquires the String instance monitor.

OTHER TIPS

But according to java spec , all objects of same type(class) on heap share single Class object. So how can this be true for multi-thread synchronized access to Objects?

Only synchronized static methods would require a thread to acquire the class object's lock. All the synchronized instance methods would need the related instance object's lock which isn't shared.

But according to java spec , all objects of same type(class) on heap share single Class object. So how can this be true for multi-thread synchronized access to Objects?

Class level locks make more sense in static methods. If you use the synchronized keyword on a static method, the object whose monitor is used for the lock is the class object, i.e. the one represented by the literal Class.class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top