ITeye博客

支持并发的单例模式

coolwolf911 · 2010-05-20 00:49 · 编程语言 · Markdown

DCL例子



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


Initialize-On-Demand



public class Foo {
    // 似有静态内部类, 只有当有引用时, 该类才会被装载
    private static class LazyFoo {
       public static Foo foo = new Foo();
    }
 
    public static Foo getInstance() {
       return LazyFoo.foo;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。