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;
}
}