单态模式

今天和师兄聊起我们事务管理框架的实现时他提到了“单态”,我——“小菜”赶紧来恶补一下。。。

 

这篇文章写的有点散,现总结如下,实现单态的方法:

1. 用Statice 定义一个实例:private static Singleton instance;

2. 用Synchronized修饰一个方法,getInstance(),该方法返回一个实例;

3. 这样用synchronized的方法消耗太大,所以如果要求高可以用其修饰一个代码块。具体比较复杂。

 

 

单态定义:
        Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。

        Singleton模式就为我们提供了这样实现的可能。使用Singleton的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收(garbage collection)。

使用Singleton注意事项:
        有时在某些情况下,使用Singleton并不能达到Singleton的目的,如有多个Singleton对象同时被不同的类装入器装载;在EJB这样的分布式系统中使用也要注意这种情况,因为EJB是跨服务器,跨JVM的

单态模式的演化:
        单态模式是个简单的模式,但是这个简单的模式也有很多复杂的东西。

(注意:在这里补充一下,现在单态模式其实有一个写法是不错的见这里:http://www.blogjava.net/dreamstone/archive/2007/02/27/101000.html,但还是建议看完这篇文章,因为解释的事情是不一样的,这里说的是为什么double-checked不能使用.)
一,首先最简单的单态模式,单态模式1

 

java 代码
 
  1. import java.util.*;  
  2. class Singleton  
  3. {  
  4.   private static Singleton instance;  
  5.   private Vector v;  
  6.   private boolean inUse;  
  7.   
  8.   private Singleton()  
  9.   {  
  10.     v = new Vector();  
  11.     v.addElement(new Object());  
  12.     inUse = true;  
  13.   }  
  14.   
  15.   public static Singleton getInstance()  
  16.   {  
  17.     if (instance == null)          //1  
  18.       instance = new Singleton();  //2  
  19.     return instance;               //3  
  20.   }  
  21. }  


java 代码

  1. import java.util.*;  
  2. class Singleton  
  3. {  
  4.   private static Singleton instance;  
  5.   private Vector v;  
  6.   private boolean inUse;  
  7.   
  8.   private Singleton()  
  9.   {  
  10.     v = new Vector();  
  11.     v.addElement(new Object());  
  12.     inUse = true;  
  13.   }  
  14.   
  15.   public static Singleton getInstance()  
  16.   {  
  17.     if (instance == null)          //1  
  18.       instance = new Singleton();  //2  
  19.     return instance;               //3  
  20.   }  
  21. }  

        这个单态模式是不安全的,为什么说呢 ?因为没考虑多线程,如下情况
        Thread 1 调用getInstance() 方法,并且判断instance是null,然後进入if模块,在实例化instance之前,Thread 2抢占了Thread 1的cpu。Thread 2 调用getInstance() 方法,并且判断instance是null,然後进入if模块,Thread 2 实例化instance 完成,返回Thread 1 再次实例化instance
        这个单态已经不在是单态

 

二,为了解决刚才的问题:单态模式2

java 代码
 
  1. public static synchronized Singleton getInstance()  
  2. {  
  3.   if (instance == null)          //1  
  4.     instance = new Singleton();  //2  
  5.   return instance;               //3  
  6. }  

        采用同步来解决,这种方式解决了问题,但是仔细分析正常的情况下只有第一次时候,进入对象的实例化,须要同步,其它时候都是直接返回已经实例化好的instance不须要同步,大家都知到在一个多线程的程序中,如果同步的消耗是很大的,很容易造成瓶颈

 

三,为了解决上边的问题:单态模式3

java 代码
 
  1. public static Singleton getInstance()  
  2. {  
  3.   if (instance == null)  
  4.   {  
  5.     synchronized(Singleton.class) {  
  6.       instance = new Singleton();  
  7.     }  
  8.   }  
  9.   return instance;  
  10. }  

        同步改成块同步,而不使用函数同步,但是仔细分析,又回到了模式一的状态,再多线程的时候根本没有解决问题

 

四,为了对应上边的问题:单态模式4,也就是很多人采用的Double-checked locking

java 代码
 
  1. public static Singleton getInstance()  
  2. {  
  3.   if (instance == null)  
  4.   {  
  5.     synchronized(Singleton.class) {  //1  
  6.       if (instance == null)          //2  
  7.         instance = new Singleton();  //3  
  8.     }  
  9.   }  
  10.   return instance;  
  11. }  

    这样,模式一中提到的问题解决了。不会出现多次实例化的现象。当第一次进入的时候,保正实例化时候的单态,在实例化后,多线程访问的时候直接返回,不须要进入同步模块,既实现了单态,又没有损失性能。表面上看我们的问题解决了,但是再仔细分析:
我们来假象这中情况:
        Thread 1 :进入到//3位置,执行new Singleton(),但是在构造函数刚刚开始的时候被Thread2抢占cpu
        Thread 2 :进入getInstance(),判断instance不等于null,返回instance,
        (instance已经被new,已经分配了内存空间,但是没有初始化数据)
        Thread 2 :利用返回的instance做某些操做,失败或者异常
        Thread 1 :取得cpu初始化完成
        过程中可能有多个线程取到了没有完成的实例,并用这个实例作出某些操做。
-----------------------------------------
出现以上的问题是因为
mem = allocate();             //分配内存
instance = mem;               //标记instance非空
                              //未执行构造函数,thread 2从这里进入
ctorSingleton(instance);      //执行构造函数
                              //返回instance

六:好了,上边证明Double-checked locking可能出现取出错误数据的情况,那么我们还是可以解决的

java 代码
 
  1. public static Singleton getInstance()  
  2. {  
  3.   if (instance == null)  
  4.   {  
  5.     synchronized(Singleton.class) {      //1  
  6.       Singleton inst = instance;         //2  
  7.       if (inst == null)  
  8.       {  
  9.         synchronized(Singleton.class) {  //3  
  10.           inst = new Singleton();        //4  
  11.         }  
  12.         instance = inst;                 //5  
  13.       }  
  14.     }  
  15.   }  
  16.   return instance;  
  17. }  

利用Double-checked locking 两次同步,中间变量,解决上边的问题。
(下边这段话我只能简单的理解,翻译过来不好,所以保留原文,list 7是上边的代码,list 8是下边的
The code in Listing 7 doesn't work because of the current definition of the memory model.
 The Java Language Specification (JLS) demands that code within a synchronized block
 not be moved out of a synchronized block. However, it does not say that
 code not in a synchronized block cannot be moved into a synchronized block.
A JIT compiler would see an optimization opportunity here.
This optimization would remove the code at
//4 and the code at //5, combine it and generate the code shown in Listing 8:)
------------------------------------------------- 
list 8
java 代码
 
  1. public static Singleton getInstance()  
  2. {  
  3.   if (instance == null)  
  4.   {  
  5.     synchronized(Singleton.class) {      //1  
  6.       Singleton inst = instance;         //2  
  7.       if (inst == null)  
  8.       {  
  9.         synchronized(Singleton.class) {  //3  
  10.           //inst = new Singleton();      //4  
  11.           instance = new Singleton();                
  12.         }  
  13.         //instance = inst;               //5  
  14.       }  
  15.     }  
  16.   }  
  17.   return instance;  
  18. }  

If this optimization takes place, you have the same out-of-order write problem we discussed earlier.
如果这个优化发生,将再次发生上边提到的问题,取得没有实例化完成的数据。
-------------------------------------------------

 

以下部分为了避免我翻译错误误导打家,保留原文

Another idea is to use the keyword volatile for the variables inst and instance.
According to the JLS (see Resources), variables declared volatile are supposed to
be sequentially consistent, and therefore, not reordered.
But two problems occur with trying to use volatile to fix the problem with
double-checked locking:

The problem here is not with sequential consistency.
Code is being moved, not reordered.

Many JVMs do not implement volatile correctly regarding sequential consistency anyway.
The second point is worth expanding upon. Consider the code in Listing 9:

Listing 9. Sequential consistency with volatile

java 代码
 
  1. class test  
  2. {  
  3.   private volatile boolean stop = false;  
  4.   private volatile int num = 0;  
  5.   
  6.   public void foo()  
  7.   {  
  8.     num = 100;    //This can happen second  
  9.     stop = true;  //This can happen first  
  10.     //...  
  11.   }  
  12.   
  13.   public void bar()  
  14.   {  
  15.     if (stop)  
  16.       num += num;  //num can == 0!  
  17.   }  
  18.   //...  
  19. }  
According to the JLS, because stop and num are declared volatile,

they should be sequentially consistent. This means that if stop is ever true,
num must have been set to 100.
However, because many JVMs do not implement the sequential consistency feature of volatile,
you cannot count on this behavior.
Therefore, if thread 1 called foo and thread 2 called bar concurrently,
thread 1 might set stop to true before num is set to 100.
This could lead thread 2 to see stop as true, but num still set to 0.
There are additional problems with volatile and the atomicity of 64-bit variables,
but this is beyond the scope of this article.
See Resources for more information on this topic.

简单的理解上边这段话,使用volatile有可能能解决问题,volatile被定义用来保正一致性,但是很多虚拟机
并没有很好的实现volatile,所以使用它也会存在问题。

最终的解决方案:
 (1),单态模式2,使用同步方法
 (2),放弃同步,使用一个静态变量,如下

 

java 代码
 
  1. class Singleton  
  2. {  
  3.   private Vector v;  
  4.   private boolean inUse;  
  5.   private static Singleton instance = new Singleton();  
  6.   
  7.   private Singleton()  
  8.   {  
  9.     v = new Vector();  
  10.     inUse = true;  
  11.     //...  
  12.   }  
  13.   
  14.   public static Singleton getInstance()  
  15.   {  
  16.     return instance;  
  17.   }  
  18. }  

但使用静态变量也会存在问题,问题见 这篇文章

 

而且如在文章开头提到的,使用EJB跨服务器,跨JVM的情况下,单态更是问题

好了是不是感觉单态模式根本没法使用了,其实上边都是特殊情况,这中特殊情况的出现是有条件的,只要
根据你的具体应用,回避一些,就能解决问题,所以单态还是可以使用的。但是在使用前慎重,自己考虑好自己
的情况适合哪种情况。

转载于:https://www.cnblogs.com/malin0614/archive/2009/03/30/1425329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值