Java的4种单例模式
--------------------------------------------------------------------------------
第一种:线程不安全,不正确的写法
class Singleton{
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
--------------------------------------------------------------------------------
第二种:线程安全,但高并发不是很理想的写法:
class Singleton{
private static Singleton instance;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
--------------------------------------------------------------------------------
第三种:线程安全,性能又高,这种写法最为常见:
class Singleton{
private static Singleton instance;
private static byte[] lock=new byte[0];
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(instance==null){
synchronized(lock){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
--------------------------------------------------------------------------------
第四种:线程安全,性能又高,这种写法也最为常见:
class Singleton{
private static Singleton instance;
private static ReentrantLock lock=new ReentrantLock ();
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(instance==null){
lock.lock();
if(instance==null){
instance=new Singleton();
}
lock.unlock();
}
return instance;
}
}