Java中的线程安全多圈

时间:2012-06-20 19:33:49

标签: java multithreading thread-safety singleton multiton

给出以下多项:

public class Multiton 
{
    private static final Multiton[] instances = new Multiton[...];

    private Multiton(...) 
    {
        //...
    }

    public static Multiton getInstance(int which) 
    {
        if(instances[which] == null) 
        {
            instances[which] = new Multiton(...);
        }

        return instances[which];
    }
}

如果没有getInstance()方法的昂贵同步和双重检查锁定的争议,我们如何保持线程安全和懒惰?提到了一种有效的单身人士方式here,但似乎并没有扩展到多人。

5 个答案:

答案 0 :(得分:15)

更新:使用Java 8,它可以更简单:

public class Multiton {
    private static final ConcurrentMap<String, Multiton> multitons = new ConcurrentHashMap<>();

    private final String key;
    private Multiton(String key) { this.key = key; }

    public static Multiton getInstance(final String key) {
        return multitons.computeIfAbsent(key, Multiton::new);
    }
}

嗯,这很好!


原始答案

这是一个以the Memoizer pattern as described in JCiP为基础的解决方案。它使用ConcurrentHashMap,就像其他答案之一一样,但它不是直接存储Multiton实例,而是可以导致创建未使用的实例,而是存储导致创建Multiton的计算。该附加层解决了未使用实例的问题。

public class Multiton {

    private static final ConcurrentMap<Integer, Future<Multiton>> multitons = new ConcurrentHashMap<>();
    private static final Callable<Multiton> creator = new Callable<Multiton>() {
        public Multiton call() { return new Multiton(); }
    };

    private Multiton(Strnig key) {}

    public static Multiton getInstance(final Integer key) throws InterruptedException, ExecutionException {
        Future<Multiton> f = multitons.get(key);
        if (f == null) {
            FutureTask<Multiton> ft = new FutureTask<>(creator);
            f = multitons.putIfAbsent(key, ft);
            if (f == null) {
                f = ft;
                ft.run();
            }
        }
        return f.get();
    }
}

答案 1 :(得分:5)

这将为您的Multitons提供线程安全存储机制。唯一的缺点是可以创建一个不会在 putIfAbsent() 调用中使用的Multiton。可能性很小,但确实存在。当然,在它发生的可能性很小的情况下,它仍然没有造成任何伤害。

从好的方面来说,不需要预先分配或初始化,也没有预定义的大小限制。

private static ConcurrentHashMap<Integer, Multiton> instances = new ConcurrentHashMap<Integer, Multiton>();

public static Multiton getInstance(int which) 
{
    Multiton result = instances.get(which);

    if (result == null) 
    {
        Multiton m = new Multiton(...);
        result = instances.putIfAbsent(which, m);

        if (result == null)
            result = m;
    }

    return result;
}

答案 2 :(得分:4)

你可以使用一组锁,至少可以同时获得不同的实例:

private static final Multiton[] instances = new Multiton[...];
private static final Object[] locks = new Object[instances.length];

static {
    for (int i = 0; i < locks.length; i++) {
        locks[i] = new Object();
    }
}

private Multiton(...) {
    //...
}

public static Multiton getInstance(int which) {
    synchronized(locks[which]) {
        if(instances[which] == null) {
            instances[which] = new Multiton(...);
        }
        return instances[which];
    }
}

答案 3 :(得分:3)

随着Java 8的出现以及ConcurrentMap和lambdas的一些改进,现在可以以更加整洁的方式实现Multiton(甚至可能是Singleton):< / p>

public class Multiton {
  // Map from the index to the item.
  private static final ConcurrentMap<Integer, Multiton> multitons = new ConcurrentHashMap<>();

  private Multiton() {
    // Possibly heavy construction.
  }

  // Get the instance associated with the specified key.
  public static Multiton getInstance(final Integer key) throws InterruptedException, ExecutionException {
    // Already made?
    Multiton m = multitons.get(key);
    if (m == null) {
      // Put it in - only create if still necessary.
      m = multitons.computeIfAbsent(key, k -> new Multiton());
    }
    return m;
  }
}

我怀疑 - 虽然这会让我感到不舒服 - getInstance可以进一步最小化:

// Get the instance associated with the specified key.
public static Multiton getInstance(final Integer key) throws InterruptedException, ExecutionException {
  // Put it in - only create if still necessary.
  return multitons.computeIfAbsent(key, k -> new Multiton());
}

答案 4 :(得分:2)

您正在寻找AtomicReferenceArray

public class Multiton {
  private static final AtomicReferenceArray<Multiton> instances = new AtomicReferenceArray<Multiton>(1000);

  private Multiton() {
  }

  public static Multiton getInstance(int which) {
    // One there already?
    Multiton it = instances.get(which);
    if (it == null) {
      // Lazy make.
      Multiton newIt = new Multiton();
      // Successful put?
      if ( instances.compareAndSet(which, null, newIt) ) {
        // Yes!
        it = newIt;
      } else {
        // One appeared as if by magic (another thread got there first).
        it = instances.get(which);
      }
    }

    return it;
  }
}