寻找带有函数对象的并发哈希表

3
如果我看Java中的ConcurrentHashMap,特别是putIfAbsent方法,这个方法的典型用法是:
ConcurrentMap<String,Person>  map = new ConcurrentHashMap<>();
map.putIfAbsent("John",new Person("John"));

问题在于Person对象总是被初始化。
是否有一些帮助集合(也许是一些提供此功能的Java框架)
能够给我类似于ConcurrentHashMap的行为,能够利用函数器或任何其他方法来构造值对象,
并且只有在映射不包含给定键的值时才会调用构建代码(即functor.execute())?

1
有趣的事实:Java 8的ConcurrentHashMap将直接支持此功能。 - Louis Wasserman
1个回答

2

唯一的方法是使用锁定。您可以通过首先进行检查来最小化其影响。

if(!map.containsKey("John"))
    synchronized(map) {
        if(!map.containsKey("John"))
           map.put("John", new Person("John"));
    }

你需要锁定的原因是,在创建Person时,你需要持有map以防止其他线程尝试同时添加相同的对象。ConcurrentMap不直接支持此类阻塞操作。
如果你需要将锁定最小化到特定的键,则可以执行以下操作。
ConcurrentMap<String, AtomicReference<Person>> map = new ConcurrentHashMap<String, AtomicReference<Person>>();

String name = "John";

AtomicReference<Person> personRef = map.get(name);
if (personRef == null)
    map.putIfAbsent(name, new AtomicReference<Person>());
personRef = map.get(name);
if (personRef.get() == null)
    synchronized (personRef) {
        if (personRef.get() == null)
            // can take a long time without blocking use of other keys.
            personRef.set(new Person(name));
    }
Person person = personRef.get();

ه¯¹ن؛ژهژںه­گه¼•ç”¨ه’Œن½؟用ConcurrentMapوژ¥هڈ£ï¼Œç»™ن؛ˆ+1م€‚ - Adam Arold

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接