26

要执行无锁和无等待延迟初始化,我执行以下操作:

private AtomicReference<Foo> instance = new AtomicReference<>(null);  

public Foo getInstance() {
   Foo foo = instance.get();
   if (foo == null) {
       foo = new Foo();                       // create and initialize actual instance
       if (instance.compareAndSet(null, foo)) // CAS succeeded
           return foo;
       else                                   // CAS failed: other thread set an object 
           return instance.get();             
   } else {
       return foo;
   }
}

它工作得很好,除了一件事:如果两个线程看到 instance null,它们都会创建一个新对象,只有一个幸运的是通过 CAS 操作设置它,这会导致资源浪费。

有没有人建议另一种无锁延迟初始化模式,它降低了两个并发线程创建两个昂贵对象的可能性?

4

5 回答 5

22

如果你想要真正的无锁,你将不得不做一些旋转。您可以拥有一个线程“赢得”创建权,但其他线程必须旋转直到准备好。

private AtomicBoolean canWrite = new AtomicBoolean(false);  
private volatile Foo foo; 
public Foo getInstance() {
   while (foo == null) {
       if(canWrite.compareAndSet(false, true)){
           foo = new Foo();
       }
   }
   return foo;
}

这显然存在忙于旋转的问题(您可以在其中放置 sleep 或 yield ),但我可能仍会推荐Initialization on demand

于 2015-05-15T18:42:12.763 回答
4

我认为您需要为对象创建本身进行一些同步。我会做:

// The atomic reference itself must be final!
private final AtomicReference<Foo> instance = new AtomicReference<>(null);
public Foo getInstance() {
  Foo foo = instance.get();
  if (foo == null) {
    synchronized(instance) {
      // You need to double check here
      // in case another thread initialized foo
      Foo foo = instance.get();
      if (foo == null) {
        foo = new Foo(); // actual initialization
        instance.set(foo);
      }
    }
  }
  return foo;
}

这是一种非常常见的模式,尤其是对于懒惰的单身人士。双重检查锁定synchronized将块实际执行的次数降至最低。

于 2015-05-15T18:55:14.377 回答
0

我可能会使用惰性初始化单例模式:

private Foo() {/* Do your heavy stuff */}

private static class CONTAINER {
 private static final Foo INSTANCE = new Foo();
}

public static Foo getInstance() {
 return CONTAINER.INSTANCE;
}

我实际上没有看到任何理由为自己使用 AtomicReference 成员字段。

于 2015-05-27T14:38:30.570 回答
0

使用另一个volatile变量来锁定呢?你可以用新变量做双锁吗?

于 2015-05-28T06:35:32.687 回答
-1

我不确定最终结果是否应该以性能为中心,如果是,下面不是解决方案。例如,请您检查两次,然后在第一次检查调用 thread.sleep 方法后随机毫秒小于 100 毫秒。

private AtomicBoolean canWrite = new AtomicBoolean(false);  
private volatile Foo foo; 
public Foo getInstance() {
   if(foo==null){
          Thread.Sleep(getRandomLong(50)) // you need to write method for it
         if(foo==null){
            foo = new Foo();
      }
   }
   return foo;
}
于 2015-05-26T17:58:31.467 回答