鉴于以下多态:
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()方法同步和双重检查锁定争议的情况下使它保持线程安全和懒惰?这里提到了单例的有效方法,但似乎并没有扩展到多例。
这将为你提供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; }
使用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); } }