单例类报空指针
关键字: 单例模式
今天写了一个并发安全的懒汉模式单例类。代码如下:
public class Config { private static Config instance = null; private Properties properties = null; private Config() { } public static Config getInstance() { synchronized(instance ){ if (instance == null) { instance = new Config(); instance.init(); } } return instance; } /** * 初始化配置文件 */ public void init(){ try{ InputStream is = Config.class.getResourceAsStream("/config.properties"); properties = new Properties(); properties.load(is); }catch (Exception e){ throw new RuntimeException("Failed to get properties!"); } } /** * 根据key值取得对应的value值 * @param key * @return */ public String getValue(String key) { return properties.getProperty(key); } /** * @return the properties */ public Properties getProperties() { return properties; } } |
程序部署后,一直在synchronized(instance )报空指针,以前大意,觉得该代码没有问题。最后在main函数下执行代码:
synchronized(instance ){ if (instance == null) { instance = new Config(); instance.init(); } } |
也报空指针,仔细想了一下,同步的时候,锁定一个null,是没有任何意义的。
正确代码段如下:
public static Config getInstance() { if (instance == null) { synchronized(Config.class){ instance = new Config(); instance.init(); } } return instance; } |
本文固定链接: http://www.chepoo.com/reported-null-pointer-singleton-class.html | IT技术精华网