Java 寻找带有函子的并发映射

Java 寻找带有函子的并发映射,java,multithreading,concurrency,java.util.concurrent,Java,Multithreading,Concurrency,Java.util.concurrent,如果我看一下java上的ConcurrentHashMap,特别是putIfAbsent方法,该方法的典型用法是: ConcurrentMap<String,Person> map = new ConcurrentHashMap<>(); map.putIfAbsent("John",new Person("John")); ConcurrentMap=new ConcurrentHashMap(); 地图。putIfAbsent(“约翰”),新人(“约翰”); 问


如果我看一下java上的ConcurrentHashMap,
特别是putIfAbsent方法,该方法的典型用法是:

ConcurrentMap<String,Person>  map = new ConcurrentHashMap<>();
map.putIfAbsent("John",new Person("John"));
ConcurrentMap=new ConcurrentHashMap();
地图。putIfAbsent(“约翰”),新人(“约翰”);
问题是Person对象总是初始化的
是否有一些帮助程序集合(可能是提供此功能的java框架)
这将给我ConcurrentHashMap类似的行为,它将使用函子或任何其他方法来构造值对象,

只有当映射不包含给定键的值时,才会调用构造代码(即-functor.execute())

执行此操作的唯一方法是使用锁定。通过先检查,可以将此影响降至最低

if(!map.containsKey("John"))
    synchronized(map) {
        if(!map.containsKey("John"))
           map.put("John", new Person("John"));
    }
需要锁定的原因是,您需要在创建Person时保持映射,以防止其他线程同时尝试添加同一对象。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=new ConcurrentHashMap();
字符串name=“John”;
AtomicReference personRef=map.get(名称);
if(personRef==null)
putIfAbsent(名称,new AtomicReference());
personRef=map.get(name);
if(personRef.get()==null)
已同步(personRef){
if(personRef.get()==null)
//可能需要很长时间,而不会阻塞其他键的使用。
personRef.set(新人员(姓名));
}
Person=personRef.get();

+1用于原子引用和使用
ConcurrentMap
接口。有趣的事实:Java8
ConcurrentHashMap
将直接支持这一点。