java单例模式的9种实现方式
一.饿汉式
public class singleton {
private static singleton instance = new singleton();
private singleton (){
}
public static singleton getinstance() {
return instance;
}
}
jdk中,java.lang.runtime就是典型的使用饿汉式的单例模式
二.懒汉式,线程不安全
public class singleton {
private static singleton instance;
private singleton (){
}
public static singleton getinstance() {
if (instance == null) {
instance = new singleton();
}
return instance;
}
}
三.懒汉式,线程安全
public class singleton {
private static singleton instance;
private singleton (){
}
public static synchronized singleton getinstance() {
if (instance == null) {
instance = new singleton();
}
return instance;
}
}
四.双检锁/双重校验锁(dcl,即 double-checked locking)
jdk 版本:jdk1.5 起
public class singleton {
private volatile static singleton singleton;
private singleton (){
}
public static singleton getsingleton() {
if (singleton == null) {
synchronized (singleton.class) {
if (singleton == null) {
singleton = new singleton();
}
}
}
return singleton;
}
}
五.静态内部类
public class singleton {
private static class singletonholder {
private static final singleton instance = new singleton();
}
private singleton (){
}
public static final singleton getinstance() {
return singletonholder.instance;
}
}
六.枚举
jdk 版本:jdk1.5 起
public enum singleton {
instance;
public void whatevermethod() {
}
}
七.双检锁/双重校验锁(dcl,即 double-checked locking)(加volatile)
jdk 版本:jdk1.5 起
public class singleton {
# 使用volatile设置内存屏障,确保线程访问资源可见性。
private volatile static singleton singleton;
private singleton (){
}
public static singleton getsingleton() {
if (singleton == null) {
synchronized (singleton.class) {
if (singleton == null) {
singleton = new singleton();
}
}
}
return singleton;
}
}
八.使用threadlocal实现单例
public class singleton {
// 用空间换时间
private static final threadlocal tl = new threadlocal();
@override
protected singleton initialvalue() {
return new singleton();
}
private singleton() {
}
public static singleton getinstance() {
return tl.get();
}
}
九.使用cas锁实现单例
private static final atomicreference instance = new atomicreference();
private singleton() {
}
public static final singleton getinstance() {
for (; ; ) {
singleton current = instance.get();
if (current != null) {
return current;
}
current = new singleton();
if (instance.compareandset(null, current)) {
return current;
}
}
}