我有一个ConcurrentMap <String,SomeObject>对象。 我想编写一个方法,如果它存在,将返回SomeObject值,或者创建一个新的SomeObject,将它放在Map中,如果它不存在则返回它。
理想情况下,我可以使用ConcurrentMap的putIfAbsent(key, new SomeObject(key)) ,但这意味着我每次都创建一个新的SomeObject(key),这看起来非常浪费。
所以我使用了以下代码,但我不确定这是处理这个问题的最佳方法:
public SomeValue getSomevalue(String key){ SomeValue result = concurrentMap.get(key); if (result != null) return result; synchronized(concurrentMap){ SomeValue result = concurrentMap.get(key); if (result == null){ result = new SomeValue(key); concurrentMap.put(key, result); } return result; } }I have a ConcurrentMap<String, SomeObject> object. I want to write a method that would return the SomeObject value if it exists, or create a new SomeObject, put it in the Map, and return it if it doesn't exist.
Ideally, I could use ConcurrentMap's putIfAbsent(key, new SomeObject(key)), but that means that I create a new SomeObject(key) each time, which seems very wasteful.
So I resorted to the following code, but am not sure that it's the best way to handle this:
public SomeValue getSomevalue(String key){ SomeValue result = concurrentMap.get(key); if (result != null) return result; synchronized(concurrentMap){ SomeValue result = concurrentMap.get(key); if (result == null){ result = new SomeValue(key); concurrentMap.put(key, result); } return result; } }最满意答案
理想情况下,我可以使用ConcurrentMap的putIfAbsent(key,new SomeObject(key)),但这意味着我每次都创建一个新的SomeObject(key),这看起来非常浪费。
然后使用computeIfAbsent :
concurrentMap.computeIfAbsent(key, SomeObject::new);使用与ConcurrentMap synchronized不会阻止其他线程在synchronized块的中间对地图执行操作。 ConcurrentMap不承诺使用map的监视器进行同步,并且ConcurrentHashMap和ConcurrentSkipListMap都不会在地图对象上同步。
请注意,ConcurrentMap接口不保证该值仅计算一次,或者如果该键已存在则不会计算该值。 ConcurrentHashMap产生了这些承诺,但ConcurrentSkipListMap没有。
Ideally, I could use ConcurrentMap's putIfAbsent(key, new SomeObject(key)), but that means that I create a new SomeObject(key) each time, which seems very wasteful.
Then use computeIfAbsent:
concurrentMap.computeIfAbsent(key, SomeObject::new);Using synchronized with a ConcurrentMap doesn't prevent other threads from performing operations on the map in the middle of the synchronized block. ConcurrentMap doesn't promise to use the map's monitor for synchronization, and neither ConcurrentHashMap nor ConcurrentSkipListMap synchronize on the map object.
Note that the ConcurrentMap interface doesn't promise that the value will only be computed once, or that the value won't be computed if the key is already present. ConcurrentHashMap makes these promises, but ConcurrentSkipListMap doesn't.
更多推荐
发布评论