对 java ConcurrentHashMap 中的值进行排序
我有以下用于对 ConcurrentHashMap 进行排序的代码:
ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
....
List<String> list = new ArrayList<String>(text.values());
Collections.sort(list);
抛出 NoSuchElementException:
Caused by: java.util.NoSuchElementException
at library.ArrayList$Itr.next(ArrayList.java:1232)
at library.ArrayList$ListItr.next(ArrayList.java:1263)
at java.util.Collections.sort(Collections.java:120)
我不知道为什么。有什么想法吗?
I have the following code for sorting a ConcurrentHashMap:
ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>();
....
List<String> list = new ArrayList<String>(text.values());
Collections.sort(list);
Which throws a NoSuchElementException:
Caused by: java.util.NoSuchElementException
at library.ArrayList$Itr.next(ArrayList.java:1232)
at library.ArrayList$ListItr.next(ArrayList.java:1263)
at java.util.Collections.sort(Collections.java:120)
And I can't work out why. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 java api
我在本地测试了以下代码
(使用 Eclipse jdk 1.5),得到了预期的输出。在将一些键值对放入 ConcurrentHashMap 后,我还运行了本地测试,没有出现任何问题。根据我的成功,似乎以下一项(或两项)导致了我们的结果之间的差异。
A) 我们使用不同的类实现(我使用 jdk 1.5 中的 java.util.concurrent.ConcurrentHashMap、java.util.List、java.util.ArrayList)
B) 您正在修改 ArrayList 的内容或 ConcurrentHashMap ,而迭代器正在迭代所述对象的内容。运行排序时是否出现异常?我最好的猜测是,在您排序时,另一个线程正在干扰您的 ArrayList(因为 ConcurentHashMap 应该是线程安全的)。
According to the java api
I tested the following code locally
(with Eclipse jdk 1.5) I get the expected output. I also ran my local test after putting some key-value pairs into the ConcurrentHashMap and had no problems. Based on my successes, it would seem that one (or both) of the following is causing the discrepancy between our results.
A) We are using different class implementations (I use java.util.concurrent.ConcurrentHashMap, java.util.List, java.util.ArrayList from jdk 1.5)
B) You are modifying the contents of
ArrayList
orConcurrentHashMap
WHILE an iterator is iterating through the contents of said object. Does the exception occur while running the sort? My best guess is another thread is messing with yourArrayList
(sinceConcurentHashMap
is supposed to be thread safe) while you are sorting.没有必要创建一个新的 ArrayList 来进行排序,因此,你可以这样做:
:EOF
It's unnessary to create a new ArrayList for sorting,thus,you can do like this :
:EOF