java单例模式-双重检查最正确的写法
public class ThreadPoolInstance {
/*
*volatile:保证了new ThreadPoolInstance();过程是线程安全的
*static:你肯定得静态是变量才能作为共享的一个类对象,如果对象实例的话就不存在单例这 说。
*/
private volatile static ThreadPoolInstance instance;
/*
*私有化构造器,避免了被外部通过new创建对象
*/
private ThreadPoolInstance() throws Exception {
// 这一步主要是为了避免被反射技术创建对象
if (null != instance) {
throw new Exception("我是单例,任何情况下都不能被外部实例");
}
}
public static ThreadPoolInstance getInstance(){
// 双重检查提高了效率的同时也保证了线程安全
if (null != instance) {
synchronized (ThreadPoolInstance.class){
if (null != instance){
try {
// 这一步已经通过volatile关键字保证创建过程是线程安全,不会发生没有创建好就被使用的情况
instance = new ThreadPoolInstance();
} catch (Exception e) {
}
}
}
}
return instance;
}
}