单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
单例模式的结构 单例模式的主要有以下角色:
单例模式的实现 单例设计模式分类两种:
饿汉式:类加载就会导致该单实例对象被创建
懒汉式:类加载不会导致该单实例对象被创建,而是首次使用该对象时才会创建
饿汉式-方式1(静态变量方式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class Singleton { private Singleton () {} private static Singleton instance = new Singleton (); public static Singleton getInstance () { return instance; } }
说明:
该方式在成员位置声明Singleton类型的静态变量,并创建Singleton类的对象instance。instance对象是随着类的加载而创建的。如果该对象足够大的话,而一直没有使用就会造成内存的浪费。
饿汉式-方式2(静态代码块方式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Singleton { private Singleton () {} private static Singleton instance; static { instance = new Singleton (); } public static Singleton getInstance () { return instance; } }
说明:
该方式在成员位置声明Singleton类型的静态变量,而对象的创建是在静态代码块中,也是对着类的加载而创建。所以和饿汉式的方式1基本上一样,当然该方式也存在内存浪费问题。
懒汉式-方式1(线程不安全)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Singleton { private Singleton () {} private static Singleton instance; public static Singleton getInstance () { if (instance == null ) { instance = new Singleton (); } return instance; } }
说明:
从上面代码我们可以看出该方式在成员位置声明Singleton类型的静态变量,并没有进行对象的赋值操作,那么什么时候赋值的呢?当调用getInstance()方法获取Singleton类的对象的时候才创建Singleton类的对象,这样就实现了懒加载的效果。但是,如果是多线程环境,会出现线程安全问题。
懒汉式-方式2(线程安全)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Singleton { private Singleton () {} private static Singleton instance; public static synchronized Singleton getInstance () { if (instance == null ) { instance = new Singleton (); } return instance; } }
说明:
该方式也实现了懒加载效果,同时又解决了线程安全问题。但是在getInstance()方法上添加了synchronized关键字,导致该方法的执行效果特别低。从上面代码我们可以看出,其实就是在初始化instance的时候才会出现线程安全问题,一旦初始化完成就不存在了。
懒汉式-方式3(双重检查锁)
再来讨论一下懒汉模式中加锁的问题,对于 getInstance()
方法来说,绝大部分的操作都是读操作,读操作是线程安全的,所以我们没必让每个线程必须持有锁才能调用该方法,我们需要调整加锁的时机。由此也产生了一种新的实现模式:双重检查锁模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Singleton { private Singleton () {} private static Singleton instance; public static Singleton getInstance () { if (instance == null ) { synchronized (Singleton.class) { if (instance == null ) { instance = new Singleton (); } } } return instance; } }
双重检查锁模式是一种非常好的单例实现模式,解决了单例、性能、线程安全问题,上面的双重检测锁模式看上去完美无缺,其实是存在问题,在多线程的情况下,可能会出现空指针问题,出现问题的原因是JVM在实例化对象的时候会进行优化和指令重排序操作。
要解决双重检查锁模式带来空指针异常的问题,只需要使用 volatile
关键字, volatile
关键字可以保证可见性和有序性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Singleton { private Singleton () {} private static volatile Singleton instance; public static Singleton getInstance () { if (instance == null ) { synchronized (Singleton.class) { if (instance == null ) { instance = new Singleton (); } } } return instance; } }
小结:
添加 volatile
关键字之后的双重检查锁模式是一种比较好的单例实现模式,能够保证在多线程的情况下线程安全也不会有性能问题。
懒汉式-方式4(静态内部类方式)
静态内部类单例模式中实例由内部类创建,由于 JVM 在加载外部类的过程中, 是不会加载静态内部类的, 只有内部类的属性/方法被调用时才会被加载, 并初始化其静态属性。静态属性由于被 static
修饰,保证只被实例化一次,并且严格保证实例化顺序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Singleton { private Singleton () {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton (); } public static Singleton getInstance () { return SingletonHolder.INSTANCE; } }
说明:
第一次加载Singleton类时不会去初始化INSTANCE,只有第一次调用getInstance,虚拟机加载SingletonHolder
并初始化INSTANCE,这样不仅能确保线程安全,也能保证 Singleton 类的唯一性。
小结:
静态内部类单例模式是一种优秀的单例模式,是开源项目中比较常用的一种单例模式。在没有加任何锁的情况下,保证了多线程下的安全,并且没有任何性能影响和空间的浪费。
枚举方式
枚举类实现单例模式是极力推荐的单例实现模式,因为枚举类型是线程安全的,并且只会装载一次,设计者充分的利用了枚举的这个特性来实现单例模式,枚举的写法非常简单,而且枚举类型是所用单例实现中唯一一种不会被破坏的单例实现模式。
1 2 3 4 5 6 public enum Singleton { INSTANCE; }
说明:
枚举方式属于恶汉式方式。
存在的问题 问题演示 破坏单例模式:
使上面定义的单例类(Singleton)可以创建多个对象,枚举方式除外。有两种方式,分别是序列化和反射。
序列化反序列化
Singleton类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Singleton implements Serializable { private Singleton () {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton (); } public static Singleton getInstance () { return SingletonHolder.INSTANCE; } }
Test类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class Test { public static void main (String[] args) throws Exception { Singleton s1 = readObjectFromFile(); Singleton s2 = readObjectFromFile(); System.out.println(s1 == s2); } private static Singleton readObjectFromFile () throws Exception { ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("C:\\Users\\Think\\Desktop\\a.txt" )); Singleton instance = (Singleton) ois.readObject(); return instance; } public static void writeObject2File () throws Exception { Singleton instance = Singleton.getInstance(); ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("C:\\Users\\Think\\Desktop\\a.txt" )); oos.writeObject(instance); } }
上面代码运行结果是false
,表明序列化和反序列化已经破坏了单例设计模式。
反射
Singleton类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class Singleton { private Singleton () {} private static volatile Singleton instance; public static Singleton getInstance () { if (instance != null ) { return instance; } synchronized (Singleton.class) { if (instance != null ) { return instance; } instance = new Singleton (); return instance; } } }
Test类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class Test { public static void main (String[] args) throws Exception { Class clazz = Singleton.class; Constructor constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true ); Singleton s1 = (Singleton) constructor.newInstance(); Singleton s2 = (Singleton) constructor.newInstance(); System.out.println(s1 == s2); } }
上面代码运行结果是false
,表明序列化和反序列化已经破坏了单例设计模式
注意: 枚举方式不会出现这两个问题。
问题的解决 JDK源码解析-Runtime类 Runtime类就是使用的单例设计模式。
通过源代码查看使用的是哪儿种单例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class Runtime { private static Runtime currentRuntime = new Runtime (); public static Runtime getRuntime () { return currentRuntime; } private Runtime () {} ... }
从上面源代码中可以看出Runtime类使用的是恶汉式(静态属性)方式来实现单例模式的。
使用Runtime类中的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class RuntimeDemo { public static void main (String[] args) throws IOException { Runtime runtime = Runtime.getRuntime(); System.out.println(runtime.totalMemory()); System.out.println(runtime.maxMemory()); Process process = runtime.exec("ipconfig" ); InputStream inputStream = process.getInputStream(); byte [] arr = new byte [1024 * 1024 * 100 ]; int b = inputStream.read(arr); System.out.println(new String (arr,0 ,b,"gbk" )); } }