保持线程安全的高性能单例模式:双检锁机制:
public class Singleton {
//volatile使主内存变动实时刷新,懒加载模式 private volatile static Singleton singleton;
//将构造函数设置为private,阻止其他类直接实例化此类。 private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
保持线程安全的非lazy加载实现单例模式:
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
使单例模式在进行反序列化之后依然有效,同时保持线程安全:借助枚举类(官方推荐):
public enum SingleEnum implements Serializable { INSTANCE; private SingleEnum(){} private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
获取单例:
SingleEnum singleEnum = SingleEnum.INSTANCE;
验证使用此方式在反序列化后得到的对象仍是同一个:
public class EnumTest { public static void main(String[] args) throws IOException, ClassNotFoundException { SingleEnum singleBean = SingleEnum.INSTANCE; SingleEnum singleBean2 = null; singleBean.setContent("单例,你好"); System.out.println("实例化前的内容为"+singleBean.getContent()); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("singlebean.obj")); objectOutputStream.writeObject(singleBean); objectOutputStream.flush(); FileInputStream fileInputStream = new FileInputStream("singlebean.obj"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); singleBean2 = (SingleEnum) objectInputStream.readObject(); System.out.println("实例化后的内容为:"+singleBean2.getContent()); Boolean flag = singleBean == singleBean2; System.out.println("是否相等:"+ flag); } }
运行结果: