本文介绍了如何证明java中的HashMap不是线程安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理应用程序,它将HashMap作为共享状态。我需要通过单元测试来证明它在多线程环境中会遇到问题。

我试图通过检查这两个HashMap的大小和元素来检查sinlge线程环境和多线程环境中的应用程序状态。但似乎这并没有帮助,状态总是相同的。



是否有其他方法可以证明它或证明在地图上执行操作的应用程序可以很好地与并发请求?

解决方案

很难模拟Race,但是看到 put()的OpenJDK源代码, HashMap的方法:

  public V put(K key,V value){
if(key == null)
return putForNullKey(value);

//操作1
int hash = hash(key.hashCode());
int i = indexFor(hash,table.length); (Entry< K,V> e = table [i]; e!= null; e = e.next){
Object k; (e.hash == hash&&((k = e.key)== key || key.equals(k))){
V oldValue = e.value;
if
e.value = value;
e.recordAccess(this);
返回oldValue;
}
}

//操作2
modCount ++;

//操作3
addEntry(hash,key,value,i);
返回null;

$ / code>

正如你可以看到 put()涉及3个不同步的操作。而且复合操作是非线程安全的。所以理论上证明 HashMap 不是线程安全的。


I'm working on application, that has HashMap as shared state. I need to prove via unit tests that it will have problems in multithread environment.

I tried to check the state of application in sinlge thread environment and in multithread environment via checking the size and elements of this HashMap in both of them. But seems this doesn't help, state is always the same.

Are there any other ways to prove it or prove that application that performs operations on map is works well with concurrent requests?

解决方案

It is hard to simulate Race but looking at the OpenJDK source for put() method of HashMap:

public V put(K key, V value) {
      if (key == null)
         return putForNullKey(value);

         //Operation 1       
         int hash = hash(key.hashCode());
               int i = indexFor(hash, table.length);
               for (Entry<K,V> e = table[i]; e != null; e = e.next) {
                   Object k;
                   if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                       V oldValue = e.value;
                       e.value = value;
                       e.recordAccess(this);
                       return oldValue;
                   }
               } 

               //Operation 2
               modCount++;

               //Operation 3
               addEntry(hash, key, value, i);
               return null;
           }

As you can see put() involves 3 operations which are not synchronized. And compound operations are non thread safe. So theoretically it is proven that HashMap is not thread safe.

这篇关于如何证明java中的HashMap不是线程安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:19