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;
}
}
具体可参见(Java并发编程从入门到精通),此书非常详细的描述了多线程中的问题和知识,不得不佩服作者的项目经验和写作功底。