使用单例模式注意点:
- 私有化构造方法
- instance是singleton类的静态成员,它的初始值可以为null,也可以写成new Singleton();
- getInstance是获取单例对象的方法
- 如果单例模式的初始值为null,还未构建,则构造单例对象并返回,一般用于懒汉模式
- 如果单例对象开始就被new Singleto()主动构建,则不再需要判空操作,这种写法属于饿汉模式
饿汉式
package com.model.single;
/**
* 饿汉式单例
*/
public class Hungry {
private byte[] data1 = new byte[1024*1024];
private byte[] data2 = new byte[1024*1024];
private byte[] data3 = new byte[1024*1024];
//构造器私有
private Hungry(){}
private final static Hungry instance = new Hungry();
public static Hungry getInstance(){
return instance;
}
缺点:
饿汉式浪费内存,无论对象空间是否使用,都会将开辟的内存加载进来。
懒汉式 DCL
package com.model.single;
//懒汉式单例
public class Singleton {
private Singleton(){}
private static Singleton instance = null;
public static Singleton getInstance(){
if(instance==null){
instance = new Singleton();//非原子性操作
}
return instance;
}
}
缺陷:
单线程没问题,对于多线程来说,线程不安全。原因是singleton类被初始化时,如果两个线程同时访问getInstance()时,因为instance为null,所以两个线程同时执行new sinleton() 操作,此时,instance被构建了两次。
解决这个缺陷:双重检测机制
package com.model.single;
//懒汉式单例
public class Singleton {
private Singleton(){}
private static Singleton instance = null;
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){//同步锁
if(instance == null){ // 双重检测机制
instance = new Singleton();//非原子性操作
}
}
}
return instance;
}
}
synchronized的使用,防止new Singleton()执行多次。
进入Synchronized临界区后,还需要再做一次判空操作,当两个线程同时访问的时候,线程1构建完对象,线程2通过最初的判空验证,不做第二次判空的话,线程2还是会再次构建instance对象。
但是 new Singleton()是一个非原子性操作,会发生指令重排现象。
指令重排:
1. 分配内存空间
2. 执行构造方法,初始化对象
3. 把这个对象指向刚分配的内存地址
我们期望会按照123的顺序执行,但是这些指令顺序可以发生改变,指令重排132顺序。
为了防止指令重排,需要在instance对象前面增加一个修饰符 volatile
package com.model.single;
//懒汉式单例
public class Singleton {
private Singleton(){}
private volatile static Singleton instance = null;
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){//同步锁
if(instance == null){ // 双重检测机制
instance = new Singleton();//非原子性操作
}
}
}
return instance;
}
}
经过volatile修饰,线程执行instance = new singleto()的时候,jvm始终按照123顺序执行
-
分配对象的内存空间
-
初始化对象
-
设置instance指向刚分配的内存地址
静态内部类
package com.model.single;
// 静态内部类实现单例
public class Holder {
//构造器私有
private Holder(){}
public static Holder getInstance(){
return InnerClass.HOLDER;
}
public static class InnerClass{
private static final Holder HOLDER = new Holder();
}
}
注意事项:
1、外部类无法直接访问静态内部类InnerClass,需要调用Holder.getInstance方法的时候。才能得到单例对象HOLDER
2、HOLDER对象初始化是在调用getInstance()方法时,使得静态内部类InnerClass被加载的时候,并不是在单例Holder被加载的时候初始化。
反射机制打破单例模式的线程安全。
步骤:
1.获得单例类的构造器
Constructor declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
2.打破私有化属性,把构造器设置可访问
declaredConstructor.setAccessible(true);
3.使用newInstance()方法构造对象
LazyMan instance = declaredConstructor.newInstance();
package com.model.single;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* 懒汉式单例
*/
public class LazyMan {
private LazyMan(){
System.out.println(Thread.currentThread().getName()+"ok");
}
private volatile static LazyMan lazyMan;
public static LazyMan getInstance(){
//双重检测锁模式
if(lazyMan == null) {
synchronized (LazyMan.class) {
if (lazyMan == null) {
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
public static void main(String[] args) throws Exception {
LazyMan instance = LazyMan.getInstance();
//获得空参构造器
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
}
结果
由结果显示,反射破坏了单例的安全, 因为反射走的是无参构造,因此只需要在无参构造中加一层synchronized(LazyMan.class)就可以解决
package com.model.single;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* 懒汉式单例
*/
public class LazyMan {
private LazyMan(){
// System.out.println(Thread.currentThread().getName()+"ok");
synchronized (LazyMan.class){
if(lazyMan!=null){
throw new RuntimeException("不要试图用反射进行破坏异常");
}
}
}
private volatile static LazyMan lazyMan;
public static LazyMan getInstance(){
//双重检测锁模式
if(lazyMan == null) {
synchronized (LazyMan.class) {
if (lazyMan == null) {
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
public static void main(String[] args) throws Exception {
LazyMan instance = LazyMan.getInstance();
//获得空参构造器
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
// LazyMan instance = declaredConstructor.newInstance();
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
}
结果:
假设两个对象都是通过反射创建,单例模式依旧遭到了破坏。
package com.model.single;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* 懒汉式单例
*/
public class LazyMan {
private LazyMan(){
synchronized (LazyMan.class){
if(lazyMan!=null){
throw new RuntimeException("不要试图用反射进行破坏异常");
}
}
}
private volatile static LazyMan lazyMan;
public static LazyMan getInstance(){
//双重检测锁模式
if(lazyMan == null) {
synchronized (LazyMan.class) {
if (lazyMan == null) {
lazyMan = new LazyMan();
}
}
return lazyMan;
}
public static void main(String[] args) throws Exception {
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance = declaredConstructor.newInstance();
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
}
结果:
怎样解决两个对象都是反射创建造成的单例模式不安全问题? 红绿灯方法解决
package com.model.single;
import java.lang.reflect.Constructor;
public class LazyRedAndGreenSingle {
private static boolean shile = false;
private LazyRedAndGreenSingle(){
synchronized (LazyRedAndGreenSingle.class){
if(shile == false){
shile = true;
}else{
throw new RuntimeException("不要试图用反射进行破坏异常");
}
}
}
private volatile static LazyRedAndGreenSingle lazyRedAndGreenSingle;
public static LazyRedAndGreenSingle getInstance(){
//双重检测锁模式
if(lazyRedAndGreenSingle == null) {
synchronized (LazyRedAndGreenSingle.class) {
if (lazyRedAndGreenSingle == null) {
lazyRedAndGreenSingle = new LazyRedAndGreenSingle(); }
}
}
return lazyRedAndGreenSingle;
}
public static void main(String[] args) throws Exception {
Constructor<LazyRedAndGreenSingle> declaredConstructor = LazyRedAndGreenSingle.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyRedAndGreenSingle instance = declaredConstructor.newInstance();
LazyRedAndGreenSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
}
结果:
注:假如通过反编译找到隐藏的变量,改单例安全会再次破坏
package com.model.single;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class LazyRedAndGreenSingle {
private static boolean shile = false;
private LazyRedAndGreenSingle(){
synchronized (LazyRedAndGreenSingle.class){
if(shile == false){
shile = true;
}else{
throw new RuntimeException("不要试图用反射进行破坏异常");
}
}
}
private volatile static LazyRedAndGreenSingle lazyRedAndGreenSingle;
public static LazyRedAndGreenSingle getInstance(){
//双重检测锁模式
if(lazyRedAndGreenSingle == null) {
synchronized (LazyRedAndGreenSingle.class) {
if (lazyRedAndGreenSingle == null) {
lazyRedAndGreenSingle = new LazyRedAndGreenSingle(); }
}
}
return lazyRedAndGreenSingle;
}
public static void main(String[] args) throws Exception {
Field shile = LazyRedAndGreenSingle.class.getDeclaredField("shile");
shile.setAccessible(true);
Constructor<LazyRedAndGreenSingle> declaredConstructor = LazyRedAndGreenSingle.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyRedAndGreenSingle instance = declaredConstructor.newInstance();
shile.set(instance,false);
LazyRedAndGreenSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance.hashCode());
System.out.println(instance2.hashCode());
}
}
结果:
使用枚举实现单例模式:
package com.model.single;
import java.lang.reflect.Constructor;
//enum本身也是一个类
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance(){
return INSTANCE;
}
}
class Test{
public static void main(String[] args) throws Exception {
EnumSingle instance = EnumSingle.INSTANCE;
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
declaredConstructor.setAccessible(true);
EnumSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance);
System.out.println(instance2);
}
}
结果:
结论:
- 反射不会破坏枚举的单例模式,而且可以保证线程安全,单例对象是在枚举类被加载的时候进行初始化的。
- 反射实现单例,不仅可以防止利用反射强行构建单例对象,而且可以在枚举类对象被反序列化的时候,保证反序列化的结果是同一对象。
单例模式实现 | 是否线程安全 | 是否懒加载 | 是否防止反射破坏 |
---|---|---|---|
双重锁检测 | 是 | 是 | 否 |
静态内部类 | 是 | 是 | 否 |
枚举 | 是 | 否 | 是 |
单例模式在spring中的应用
-
spring的Bean默认的是单例的,Bean的作用域可以通过Bean标签的scope属性进行设置
-
在Spring中,bean可以被定义为两种模式:prototype(多例)和singleton(单例)
-
singleton(单例):只有一个共享的实例存在,所有对这个bean的请求都会返回这个唯一的实例。
-
prototype(多例):对这个bean的每次请求都会创建一个新的bean实例,类似于new。
<bean id="hi" class="com.sun" init-method="init" scope="singleton">
<bean id="hi" class="com.test.Hi" init-method="init" scope="prototype">