Java中没有CuncurrentSkipListMap的线程安全方法 [英] Not thread safe methods of CuncurrentSkipListMap in Java
问题描述
在我的Java项目中,我需要以多线程的方式使用TreeMap。我发现ConcurrentSkipListMap是我需要的,但有些方法不是线程安全的。其中之一 - containsKey(对象键)。以多种方式使用此方法的典型解决方案是什么?在我的程序中,我需要放置不会取代旧的密钥,如果不可能,我将放入另一个密钥而不会获得唯一密钥。应该使用什么构造而不是包含键,因为我不能丢失信息?
In my Java project I need to use TreeMap in multihreaded way. I found that ConcurrentSkipListMap is what that I need but some methods are not thread safe. One of them - containsKey(Object key). What is a typical solution for using this methods in multhreded way? In my program I need put key that will not replace old and if it's impossible I will be putting another key while will not get unique key. What construction should use instead containsKey as i can't lost information?
推荐答案
如果你担心containsKey结果在你面前陈旧可以采取行动,或关于此警告javadoc :
If you are worried about containsKey results going stale before you can act on them, or about this warning in the javadoc:
此外,不保证以原子方式执行批量操作putAll,equals,toArray,containsValue和clear 。例如,与putAll操作同时运行的迭代器可能只查看一些添加的元素。
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 :
there are methods defined on ConcurrentSkipListMap that you can use instead. For instance, see 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.
另请参阅删除和替换方法。
Also see the methods remove and replace.
这篇关于Java中没有CuncurrentSkipListMap的线程安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!