在Java ConcurrentHashMap中对值进行排序 [英] Sorting the values in a java ConcurrentHashMap

查看:240
本文介绍了在Java ConcurrentHashMap中对值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码用于对ConcurrentHashMap进行排序:

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);

哪个抛出NoSuchElementException:

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?

推荐答案

根据

NoSuchElementException 由的nextElement方法抛出 枚举表示有 枚举中没有更多元素.

NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

我在本地测试了以下代码

I tested the following code locally

ConcurrentHashMap<String, String> t = new ConcurrentHashMap<String, String>();

List<String> al = new ArrayList<String>(t.values());
Collections.sort(al);

System.out.println("no bugs");

(使用Eclipse jdk 1.5)得到了预期的输出.在将一些键值对放入ConcurrentHashMap之后,我也进行了本地测试,没有问题.根据我的成功经验,似乎以下一项(或两项)导致我们的结果之间存在差异.

(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)我们正在使用不同的类实现(我使用jdk 1.5中的java.util.concurrent.ConcurrentHashMap,java.util.List,java.util.ArrayList)

A) We are using different class implementations (I use java.util.concurrent.ConcurrentHashMap, java.util.List, java.util.ArrayList from jdk 1.5)

B)您正在修改ArrayListConcurrentHashMap的内容,同时迭代器遍历该对象的内容.运行排序时是否会发生异常?我最好的猜测是排序时,另一个线程弄乱了您的ArrayList(因为ConcurentHashMap应该是线程安全的).

B) You are modifying the contents of ArrayList or ConcurrentHashMap 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 your ArrayList (since ConcurentHashMap is supposed to be thread safe) while you are sorting.

这篇关于在Java ConcurrentHashMap中对值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆