java - Lazy initialization Singleton class with volatile variable -


i came across singleton class {lazy initialization}. code below

// singleton reference class     private static volatile fileproperties instance = null;       public static fileproperties getinstance() {             if (instance == null) {                 synchronized (fileproperties.class) {                     if (instance == null) {                         instance = new fileproperties();                     }                 }             }             return instance;         } 

my question benefit getting making instance volatile since taking care of thread safety synchronized. there benefit of volatile in scenario ?

that because double-checked locking without volatile not thread-safe in java.

the simplest way make thread-safe lazy-init singleton create class holder follows:

public class someclass {     private static class someclassholder {         public static final someclass instance = new someclass();     }      public static someclass getinstance() {        return someclassholder.instance;     }       private someclass() {}  } 

that part of code, because of jvm behavior load someclassholder , create instance of someclass on first usage of getinstance() (and not when someclass loaded classloader).

you don't need use synchronization @ all!! because jvm doing you.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -