Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort concurrentHash Map with threadsafty

I am using 'concurrentHashMap' in my 'multithreaded' application. i was able to sort it as describe here. but since i am converting hashmap to a list i am bit worried about the thred safty. My 'ConcurrentHashMap' is a static variable hence i can guarantee there will be only one instance of it. but when i am going to sort it i convert it to a list, and sort then put it back to a new concurrentHashMap.

Is this a good practice in multi-threading enlivenment?

Please let me know your thoughts and suggestions.

Thank you in advance.

like image 511
Sam Avatar asked Feb 22 '23 00:02

Sam


2 Answers

You should use a ConcurrentSkipListMap. It is thread-safe, fast and maintains ordering according to the object's comparable implementation.

like image 79
John Vint Avatar answered Feb 23 '23 14:02

John Vint


If you don't change it a lot and all you want is to have it sorted, you should use a TreeMap ** wrapped by a **Collections.synchronizedMap() call

Your code would be something like this:

public class YourClass {
  public static final Map<Something,Something> MAP = Collections.synchronizedMap( new TreeMap<Something,Something>() );
}
like image 31
Maurício Linhares Avatar answered Feb 23 '23 13:02

Maurício Linhares