java - Lazy initialization Singleton class with volatile variable -
this question has answer here:
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
Post a Comment