java单例模式

来源:互联网 发布:网络咨询师技巧 编辑:程序博客网 时间:2024/04/27 16:51

单例模式非常有用并且很常见,但是怎么创建一个安全的单例模式呢?

最常用的创建单例模式的例子是:

class Singleton{  private static Singleton instance;  private Vector v;  private boolean inUse;  private Singleton()  {    v = new Vector();    v.addElement(new Object());    inUse = true;  }  public static Singleton getInstance()  {    if (instance == null)          //1      instance = new Singleton();  //2    return instance;               //3  }}

但是这种方法是非线程安全的,如果两个以上的线程同时调用,就可以出问题。

所以引入同步机制

public static synchronized Singleton getInstance(){  if (instance == null)          //1    instance = new Singleton();  //2  return instance;               //3}

此时,由于同步,考虑到性能问题,优化方法是使用双重检查锁定机制

public static Singleton getInstance(){  if (instance == null)  {    synchronized(Singleton.class) {  //1      if (instance == null)          //2        instance = new Singleton();  //3    }  }  return instance;}

这个时候,比较好了,但是两个线程互相依赖的时候还是会有问题,所以,出现了下面一种方法:放弃同步,使用static

class Singleton{  private Vector v;  private boolean inUse;  private static Singleton instance = new Singleton();  private Singleton()  {  }  public static Singleton getInstance()  {    return instance;  }}
这种方法比较简单也很好理解。如果类中还有其他静态方法,就会初始化了此类。导致的问题是,不是通过getInstance初始化了。。。

其实,各种方法各有所爱,看情况使用。


0 0
原创粉丝点击