Search code examples
javamultithreadingsynchronizationjlsmutual-exclusion

Lock implemention on "Class" class object for synchronization


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?


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.