并发编程之单例模式
1.饿汉模式
/**
* 饿汉。即使没有使用,也会实例化,浪费堆空间
*/
public class SingletonObj01 {
private static final SingletonObj01 singleton = new SingletonObj01();
private SingletonObj01() {
}
public static SingletonObj01 getInstance() {
return singleton;
}
}
2.懒汉模式
/**
* 懒汉。懒加载,同步方法,线程安全,但是串行化执行,每次都要去竞争锁
*/
public class SingletonObj02 {
private static SingletonObj02 singleton;
private SingletonObj02() {
}
public synchronized static SingletonObj02 getInstance() {
if (singleton == null) {
singleton = new SingletonObj02();
}
return singleton;
}
}
/**
* 懒汉。double check,懒加载,线程安全,一旦实例化后就不再争夺锁。
* 但必须要加关键字volatile,否则会出现NPE,譬如在SingletonObj03构造器中引用了构建很慢的一个大对象
*/
public class SingletonObj03 {
private volatile static SingletonObj03 singleton;
private SingletonObj03() {
}
public static SingletonObj03 getInstance() {
if (singleton == null) {
synchronized (SingletonObj03.class) {
if (singleton == null) {
singleton = new SingletonObj03();
}
}
}
return singleton;
}
}
3.内部类常量模式
/**
* 懒加载,线程安全,效率还高
*/
public class SingletonObj04 {
private SingletonObj04() {
}
private static class InstanceHolder {
private static final SingletonObj04 singleton = new SingletonObj04();
}
public static SingletonObj04 getInstance() {
return InstanceHolder.singleton;
}
}
4.枚举模式
/**
* 《Effective Java》推崇的写法
*/
public class SingletonObj05 {
private SingletonObj05() {
}
private enum Singleton {
INSTANCE,;
private final SingletonObj05 singletonObj05;
Singleton() {
singletonObj05 = new SingletonObj05();
}
private SingletonObj05 getInstance() {
return singletonObj05;
}
}
public static SingletonObj05 getInstance() {
return Singleton.INSTANCE.singletonObj05;
}
}