看别人的博客有感,结合公司的项目想了下,目前在公司项目里常用的线程安全单例模式是这么写的:
public class Hxy{
private static Hxy hxy = new Hxy();
private Hxy(){
}
public static Hxy getInstance(){
return hxy;
}
}
没有使用同步锁,同样多线程安全,这看起来的话公司的这种写法在类加载的时候就会new一个对象出来,有大量的类是这么写的话,理论上这会使得在启动的时候变慢。
多线程安全单例的第二种写法,使用同步锁:
public class Hxy{
private static Hxy instance = new Hxy();
private Hxy(){
}
public static synchronized Hxy getInstance(){
if(null == instance){
instance = new Hxy();
}
return instance;
}
}
如果使用双重同步锁的话写法就有点麻烦了:
public class Hxy{
private static Hxy instance = new Hxy();
private Hxy(){
}
public static Hxy getInstance(){
if(null == instance){
synchronized(Hxy.class){
if(null == instance){
instance = new Hxy();
}
}
}
return instance;
}
}
文章说java里使用枚举作为单例类是最简单的方式来创建线程安全单例模式的方式,我来模仿下:
public class HxyFactory{
private enum HxyEnum{
singleFactory;
private Hxy instance;
HxyEnum(){
instance = new Hxy();
}
public Hxy getInstance(){
return instance;
}
}
public static Hxy getInstance(){
return HxyEnum.singleFactory.getInstance();
}
}
class Hxy{
public Hxy(){
}
}
折腾下就好了,其实我还是喜欢怎么简单怎么来,哈。