Search code examples
javasynchronizationsingletonvolatile

Does Singleton class with its instance as volatile make the instance data to be load again?


In my application Server class is load on startup and all data is cached as once.

It is a singleton class ,and its instance variable is not volatile i.e.

private static Server server;

After findbug analysis, i have to change it to volatile,(shown below

public class Server {
    private static volatile Server server;

    public static Server getInstance(){
        if(server == null){
            synchronized (Server .class) {
                if(server == null){
                    try {
                        server = new Server(....);
                    } catch (IOException e) {
                        Logger.logError(MODULE, "IO Error while creating server home location: " + strServerHome);
                        Logger.logTrace(MODULE, e);
                    }
                }
            }
        }
        return server;
    }.......
}

but after reading articles and Q/A about volatile on stack, i think volatile will make the data to be load again ,as volatile make information to be read from memory and not cache.

So should i make my variable volatile or not ?

if volatile , then do i have to load my data again & again ?


Solution

  • The generally considered safest method to create a thread-safe singleton is make it an enum...

     public enum Server{
          INSTANCE;
    
          public Server getInstance(){
              return INSTANCE;
          }
    
          private Server(){...}
    
          // rest of methods here
     }
    

    Singleton:The Enum Way