Java 中的线程安全 multiton [英] Thread safe multitons in Java

查看:26
本文介绍了Java 中的线程安全 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() 方法的昂贵同步和双重检查锁定的争议,我们如何保持线程安全和惰性?此处 提到了一种有效的单身人士方法,但这似乎没有扩展到多人.

How can we keep it thread safe and lazy without the expensive synchronization of the getInstance() method and the controversy of double-checked locking? An effective way for singletons is mentioned here but that doesn't seem to extend to multitons.

推荐答案

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

This will provide you a threadsafe storage mechanism for your Multitons. The only downside is that it is possible to create a Multiton that will not be used in the putIfAbsent() call. The possibility is small but it does exist. Of course on the remote chance it does happen, it still causes no harm.

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

On the plus side, there is no preallocation or initialization required and no predefined size restrictions.

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 中的线程安全 multiton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆