Sorting values ​​in java ConcurrentHashMap

I have the following code to sort ConcurrentHashMap:

ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>(); .... List<String> list = new ArrayList<String>(text.values()); Collections.sort(list); 

What 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 understand why. Any ideas?

+2
source share
2 answers

According to java api

NoSuchElementException Thrown by the nextElement Enumeration method 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"); 

(with Eclipse jdk 1.5) I get the expected result. I also ran a local test after entering some key-value pairs in ConcurrentHashMap and had no problems. Based on my successes, it seems that one (or both) of the following causes a mismatch between our results.

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

B) You modify the contents of an ArrayList or ConcurrentHashMap WHILE when the iterator iterates through the contents of the specified object. Does an exception occur when starting sorting? My best guess is another thread that fiddles with your ArrayList (since ConcurentHashMap must be thread safe) during sorting.

+3
source

It is not possible to create a new ArrayList for sorting, so you can do like this:

 ConcurrentHashMap<String,String> text = new ConcurrentHashMap<String,String>(); List<String> textList=text.values(); //unmodifiable List here. Collections.sort(textList);// it also can sort. 

: EOF

-1
source

Source: https://habr.com/ru/post/1404037/


All Articles