[英]Will HashMap#put/remove suffer any ConcurrentModificationException if used from multiple threads
In Test.java 在Test.java中
public static Map<String, Integer> testMap=new HashMap<String, Integer>();
In TestServlet.java 在TestServlet.java中
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Test.testMap.put("cool", 1);
}
In TestServlet2.java 在TestServlet2.java中
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Test.testMap.remove("cool");
}
In test.html
, there is a function to call TestServlet every 3 secs 在
test.html
,有一个函数每3秒调用一次TestServlet。
mTimer = setTimeout('getTest();',3000); //call TestServlet in 3 seconds
In test2.html
, there is a function to call TestServlet2 every 2 secs 在
test2.html
,有一个函数每2秒调用一次TestServlet2。
mTimer = setTimeout('getTest2();',2000); //call TestServlet in 2 seconds
Now, I run test.html
& test2.html
at the same time & no problem occur. 现在,我同时运行
test.html
和test2.html
,不会出现任何问题。
Of course, if I replace public static Map<String, Integer> testMap=new HashMap<String, Integer>();
当然,如果我替换
public static Map<String, Integer> testMap=new HashMap<String, Integer>();
with public static List<String> testList=new ArrayList<String>();
使用
public static List<String> testList=new ArrayList<String>();
, then I got ConcurrentModificationException
,然后我得到了
ConcurrentModificationException
My question is that? 我的问题是? Can
HashMap
suffer any ConcurrentModificationException
or be Thread-safe? HashMap
可以遭受任何ConcurrentModificationException
还是线程安全的?
I have not tried to modify the value of each key of the Map
so I don't know what is going on. 我没有尝试修改
Map
每个键的值,所以我不知道发生了什么。
HashMap
s are not thread safe and should be used wisely. HashMap
不是线程安全的,应该明智地使用。 If you want to use key value pairs type of data structure ConcurrentHashMap
is recommended in multithreaded environment. 如果要使用键值对,则在多线程环境中建议使用
ConcurrentHashMap
类型的数据结构。
Yes - you can see from the source code that the iterator throws such an exception: 是的-您可以从源代码中看到迭代器抛出此类异常:
808 final Entry<K,V> nextEntry() {
809 if (modCount != expectedModCount)
810 throw new ConcurrentModificationException();
And modCount
is incremented in the put
method and other places. 并且
modCount
在put
方法和其他位置增加。
Note that this is not necessarily restricted to the issue of thread-safety. 注意,这不一定限于线程安全问题。 A same-thread sequence of operations could cause the exception to be thrown if a
put
operation was done while between two iterator operations. 如果在两个迭代器操作之间执行
put
操作,则同一线程的操作序列可能导致引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.