猿问

Java中的线程安全多态

鉴于以下多态:


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


12345678_0001
浏览 355回答 3
3回答

元芳怎么了

这将为您提供Multitons的线程安全存储机制。唯一的缺点是可以创建在putIfAbsent()调用中不使用的Multiton。可能性很小,但确实存在。当然,尽管确实有发生,但仍然不会造成任何伤害。从正面看,不需要预分配或初始化,也没有预定义的大小限制。private static ConcurrentHashMap<Integer, Multiton> instances = new ConcurrentHashMap<Integer, Multiton>();public static Multiton getInstance(int which)&nbsp;{&nbsp; &nbsp; Multiton result = instances.get(which);&nbsp; &nbsp; if (result == null)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Multiton m = new Multiton(...);&nbsp; &nbsp; &nbsp; &nbsp; result = instances.putIfAbsent(which, m);&nbsp; &nbsp; &nbsp; &nbsp; if (result == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = m;&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

慕标琳琳

您可以使用一组锁,至少能够同时获取不同的实例:private static final Multiton[] instances = new Multiton[...];private static final Object[] locks = new Object[instances.length];static {&nbsp; &nbsp; for (int i = 0; i < locks.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; locks[i] = new Object();&nbsp; &nbsp; }}private Multiton(...) {&nbsp; &nbsp; //...}public static Multiton getInstance(int which) {&nbsp; &nbsp; synchronized(locks[which]) {&nbsp; &nbsp; &nbsp; &nbsp; if(instances[which] == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; instances[which] = new Multiton(...);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return instances[which];&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答