private static volatile Something instance = null; public static Something getInstance() { if (instance == null) { synchronized (XXX.class) { if (instance == null) instance = new Something(); } } return instance; }
private Something(){}
加volatile后可以在jdk1.5之后正常工作,在jdk1.5之前还是有问题的
单例模式推荐使用饿汉式,启动时直接完成初始化
参考Dong Lee的系列博客:http://ifeve.com/jmm-faq-dcl/
volatile在初始化代码块的用途:jdk一个示例