1.延迟加载,非线程安全
2.声明时进行初始化,线程安全,但如果实例很大,可能会占用空间
3.延迟加载,采用synchronized关键字,线程安全,但可能会有效率问题
4.双检锁模式其实有隐含的问题,当一个线程正在new Config4(),处于部分初始化状态,该instance可能已不为null,此时又有另一个线程访问,就会有问题。
见effective Java 48条
5.内部类的方式,既延迟加载,又可保证线程安全
总的来看,多线程使用应该推荐2,3,5
package Singleton;
/**
* Singleton
* lazy initialization
* non-synchronized
* @author cc
*/
public class Config {
private static Config instance;
private Config(){
//initiate
}
public static Config getInstance(){
//lazy initialize
if(instance == null){
instance = new Config();
}
return instance;
}
}
2.声明时进行初始化,线程安全,但如果实例很大,可能会占用空间
package Singleton;
/**
* Singleton
* eager
* thread-safe
* @author cc
*/
public class Config2 {
private static Config2 instance = new Config2();
private Config2(){
//initiate
}
public static Config2 getInstance(){
return instance;
}
}
3.延迟加载,采用synchronized关键字,线程安全,但可能会有效率问题
package Singleton;
public class Config3 {
private static Config3 instance;
private Config3(){
//initiate
}
public synchronized static Config3 getInstance(){
//lazy initialize
if(instance == null){
instance = new Config3();
}
return instance;
}
}
4.双检锁模式其实有隐含的问题,当一个线程正在new Config4(),处于部分初始化状态,该instance可能已不为null,此时又有另一个线程访问,就会有问题。
见effective Java 48条
package Singleton;
/**
* singleton
* double-checked locking
* @author cc
*/
public class Config4 {
private static Config4 instance;
private Config4(){
//initiate
}
public static Config4 getInstance(){
//lazy initialize
if(instance == null){
synchronized(Config4.class){
if(instance == null){
instance = new Config4();
}
}
}
return instance;
}
}
5.内部类的方式,既延迟加载,又可保证线程安全
package Singleton;
/**
* singleton
* inner class
* thread-safe
* @author cc
*/
public class Config5 {
private static class Config{
private static Config5 conf = new Config5();
}
private Config5(){
//initiate
}
public static Config5 getInstance(){
return Config.conf;
}
}
总的来看,多线程使用应该推荐2,3,5