Java线程安全的单例模式
2018-11-10 本文已影响0人
Seaofdesire
简单的单例模式(饿汉模式)
class SimpleSingleton {
private static SimpleSingleton ss = new SimpleSingleton();
private SimpleSingleton() {
}
public static SimpleSingleton getInstance() {
return ss;
}
}
- 程序代码加载时,单例即初始化,加重系统负载.未实现懒加载
懒加载的单例模式
class LazySingleton {
private static LazySingleton ls = null;
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (ls == null) {
ls = new LazySingleton();
}
return ls;
}
}
双锁延迟加载
class DoubleLockSingleton {
private static DoubleLockSingleton ds = null;
private DoubleLockSingleton() {
}
public static DoubleLockSingleton getInstance() {
if (ds == null) {
synchronized (DoubleLockSingleton.class) {
if (ds == null) {
ds = new DoubleLockSingleton();
}
}
}
return ds;
}
}
- 比LazySingleton锁粒度细一点
内部类实现(推荐)
class InnerSingleton {
private InnerSingleton() {
}
public static InnerSingleton getInstance() {
return InnerClass.ins;
}
private static class InnerClass {
private static final InnerSingleton ins = new InnerSingleton();
}
}
- 无锁实现懒加载的单例模式