在我的Java项目中,我需要以多种方式使用TreeMap.我发现ConcurrentSkipListMap是我需要的,但是有些方法不是线程安全的.其中之一-containsKey(Object key).以多种方式使用此方法的典型解决方案是什么?在我的程序中,我需要放置不会替换旧密钥的密钥,如果不可能的话,我将放置另一个密钥而不会获得唯一密钥.因为我不会丢失信息,所以应该使用哪种结构来代替containsKey?
解决方法:
如果您担心containsKey结果会过时,然后再对其执行操作,或者大约this warning in the javadoc:
Additionally, the bulk operations putAll, equals, toArray, containsValue, and clear are not guaranteed to be performed atomically. For example, an iterator operating concurrently with a putAll operation might view only some of the added elements.
在ConcurrentSkipListMap上定义了一些方法,您可以改用这些方法.例如,请参见putIfAbsent:
If the specified key is not already associated with a value, associate it with the given value. This is equivalent to
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
except that the action is performed atomically.
另请参阅删除和替换方法.