Java ConcurrentHashMap行为和问题
我有4个线程-2个线程更新,2个线程读取concurrentHashMap。代码如下:Java ConcurrentHashMap行为和问题,java,data-structures,concurrenthashmap,Java,Data Structures,Concurrenthashmap,我有4个线程-2个线程更新,2个线程读取concurrentHashMap。代码如下: private static ConcurrentHashMap<String, String> myHashMap = new ConcurrentHashMap<>(); private static final Object lock = new Object(); 线程3和线程4的run方法进行打印 for (Entry<String, String> entry
private static ConcurrentHashMap<String, String> myHashMap = new ConcurrentHashMap<>();
private static final Object lock = new Object();
线程3和线程4的run方法进行打印
for (Entry<String, String> entry : myHashMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
for(条目:myHashMap.entrySet()){
String key=entry.getKey();
字符串值=entry.getValue();
System.out.println(“键,+key+“值”+value);
}
上述ConcurrenHashMap代码的使用是否存在任何问题? 因为当我阅读Javadoc并搜索web时,我发现了以下声明:
至于要求,我希望并发读取而不阻塞,这就是我选择ConcurrentHashMap的原因。您可以使用并发hashmap中的putIfAbsent方法,而不是使用if-else块。其次,您不应该在并发hashmap中使用外部锁定。上述代码有任何问题吗我认为如果不知道你想做什么以及你是如何做的,我们无法回答这个问题。你的代码片段太模糊了。有关如何生成更好的代码示例的说明,请参阅。已更新代码。对值执行某些操作只意味着计算值。@Nathan Hughes我需要确保更新线程被锁定,这样只有一个线程可以执行更新,而另一个线程必须等待。你只需要假设更新线程只能为内部所有代码的原子运行。你在外部环境下使用它破坏了CHM的整个用途锁使用原子的
merge()
。问题是,由于计算的复杂性,我不能使用内置的putIfAbsent方法。为什么我们不能使用外部锁呢?使用外部锁时是否有任何意外行为?还是仅仅因为性能?我敢打赌,性能不会比使用哈希表更差,即使在读取线程上也是如此。
for (Entry<String, String> entry : myHashMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}