Sort concurrentHash cards with threadsafty

I use 'concurrentHashMap' in my multi-threaded application. I managed to sort it as described here . but since I am converting hashmap to a list, I am a little worried about thred safty. My "ConcurrentHashMap" is a static variable, so I can guarantee that there will be only one instance. but when I am going to sort it, I convert it to a list and sort it, and then bring it back to the new concurrentHashMap.

Is this good practice in multi-threaded animation?

Please let me know your thoughts and suggestions.

Thanks in advance.

+4
source share
3 answers

You must use ConcurrentSkipListMap . It is thread safe, fast, and maintains order in accordance with a comparable object implementation.

+6
source

If you don’t change it a lot and all you need to do is sort it, you should use TreeMap ** wrapped ** Collections.synchronizedMap () call

Your code will be something like this:

public class YourClass { public static final Map<Something,Something> MAP = Collections.synchronizedMap( new TreeMap<Something,Something>() ); } 
+1
source

My 'ConcurrentHashMap' is a static variable, so I can guarantee that there will be only one instance. but when I am going to sort it, I will convert it to a list and sort it, and then return it back to the new concurrentHashMap.

This is not an easy problem.

I can tell you that using ConcurrentHashMap will not make this thread safe. Also will not use the synchronizedMap wrapper. The problem is that sorting is not supported as a single atomic operation. Rather, it involves a series of API Maps operations, possibly with significant intervals between them.

I can come up with two approaches to solving this issue:

  • Avoid the need to sort first with the Card, which stores the keys in order; for example use ConcurrentSkipListMap.

  • Wrap the map class in a custom synchronized wrapper class using the synchronized sort method. The problem with this approach is that you are likely to re-add the concurrency bottleneck that you avoid using the ConcurrentHashMap.


And it is worth noting that it makes no sense to sort the HashMap or ConcurrentHashMap , because these cards will not preserve the order in which you sort the elements. You can use LinkedHashMap , which preserves the insertion order of the entry.

0
source

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


All Articles