java - Singleton Implementation example -
i trying find own way of java singleton implementation. code follows:
public class singleton{ private volatile static singleton _instance = null; private singleton(){} public static singleton getinstance(){ if (_instance == null) object obj = new object(); synchronized(obj){ if (_instance == null) _instance = new singleton(); } return _instance; } does code work? if not work, how fix it?
no, it's not correct, should synchronize on singleton.class
class singleton { private volatile static singleton _instance; private singleton(){} public static singleton getinstance(){ if (_instance == null) synchronized(singleton.class){ if (_instance == null) _instance = new singleton(); } return _instance; } } it's known double-checked locking pattern, see http://www.ibm.com/developerworks/java/library/j-dcl/index.html details
note since there's 1 method in class following serves same purpose without double-checked tricks , it's lazy too
class singleton { private static singleton _instance = new singleton(); private singleton(){} public static singleton getinstance(){ return _instance; } }
Comments
Post a Comment