13

给定以下多吨:

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() 方法同步和双重检查锁定的争议,我们如何保持线程安全和惰性?这里提到了单例的有效方法,但似乎并没有扩展到多例。

4

5 回答 5

18

更新:使用 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);
    }
}

嗯,这很好!


原始答案

这是一个基于JCiP 中描述的 Memoizer 模式的解决方案。它像其他答案之一一样使用 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();
    }
}
于 2013-08-09T14:50:08.330 回答
6

这将为您的 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;
}
于 2012-06-20T20:24:35.490 回答
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];
    }
}
于 2012-06-20T19:43:40.917 回答
3

随着 Java 8 的出现以及对ConcurrentMaplambda 的一些改进,现在可以以更整洁的方式实现 a Multiton(甚至可能是 a ):Singleton

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());
}
于 2013-12-02T15:29:34.557 回答
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;
  }
}
于 2012-06-21T01:18:52.570 回答