mardi 3 août 2021

Singleton pattern | What is the use of volatile in the code, as synchronized keyword also provides visibility grantee as per java memory model

Below is the code for singleton pattern in java that can be found across internet. My question is what is the requirement to mark instance variable as volatile because we are using synchronization in getInstance() method and this should be enough to provide visibility grantee?

public class MySingleton {
    
    private volatile static MySingleton INSTANCE;
    
    private MySingleton() {
        super();
    }
    
    public static MySingleton getInstance() {
        if(INSTANCE == null) {
            synchronized (MySingleton.class) {
                if(INSTANCE == null)
                    INSTANCE = new MySingleton();
            }
        }
        return INSTANCE;
    }

}

Aucun commentaire:

Enregistrer un commentaire