线程安全,高并发性能不高
public class SingletonOne {
private static SingletonOne instance;
private static ReentrantLock lock = new ReentrantLock();
private SingletonOne(){
}
public static SingletonOne getInstance(){
if(instance == null){
lock.lock();
if(instance == null){
instance = new SingletonOne();
}
lock.unlock();
}
return instance;
}
}
线程安全、性能高
public class SingletonTwo {
private static SingletonTwo instance;
private static byte[] lock = new byte[0];
private SingletonTwo(){
}
public static SingletonTwo getInstance(){
if(instance == null){
synchronized (lock) {
if(instance == null){
instance = new SingletonTwo();
}
}
}
return instance;
}
}