Home > Mobile >  Reflection class in synchronized block
Reflection class in synchronized block

Time:03-28

I have singleton realization

public class Singleton {

private static volatile Singleton inst;

public static Singleton instOf() {
    if (inst == null) {
        synchronized (Singleton .class) {
            if (inst == null) {
                inst = new Singleton ();
            }
        }
    }
    return inst;
}

I сan't fully understand what "synchronized (Singleton.class)" does mean? what if just synchronized (this) instead

CodePudding user response:

JVM has a monitor or otherwise called intristic flag related with the class meta information which are stored in some specific place in memory (permGen or metaspace). In that place a single monitor flag exists and is related with the class it self and not some instance of that class.

synchronized (Singleton.class) will capture this flag in permgen memory (before jdk 8) or in metaspace memory (jdk 8 and after) .

JVM also has a separate monitor flag for every class instance which is stored in heap.

synchronized (this) will capture the flag of a specific instance in heap memory which is pointed by this when that instance was invoked.

Those flags work in the same way but are just different flags. So only 1 thread can require to capture the flag and other threads should wait for this flag to be released before they can capture it and access the code. It is up to you and your requirements if you lock the static flag or the instance flag but the concept is the same. Not 2 threads can hold the same flag at the same time. 1 will block and wait for the flag to be released before it can access the synchronized code.

Note: this will not work inside a static method. In this case you have available only the flag related with the class it self. You can still though use both of those type of flags in non static method.

  • Related