The most efficient way to create data streams (Java)

I have a general map data structure that should be thread safe. Synchronized is the most efficient way to read or add to a card?

Thanks!

Edit: the data structure is a non-recoverable cache, that is, as soon as it is full, it does not update the cache. So many records initially with some readings, then he basically reads

+6
source share
4 answers

The “most effective” is relative, of course, and depends on your specific situation. But consider something like ConcurrentHashMap if you expect that there will be many threads working with the card at the same time; it is thread safe, but still allows concurrent access, unlike Hashtable or Collections.synchronizedMap() .

+6
source

It depends on how you use it in the application.

If you do a lot of reading and writing on it, ConcurrentHashMap is probably the best choice, if it mainly reads, a shared card wrapped in a collection using ReadWriteLock (since records will not be distributed, you will get quick access and lock only when writing).

Collections.synchronizedMap () is arguably the worst case scenario, as it can just give you a wrapper with all synchronized methods, avoiding it at all costs.

+3
source

In your specific use case (non-recoverable cache), a copy on the recording card will exceed both the synchronized card and ConcurrentHashMap.

See: https://labs.atlassian.com/wiki/display/CONCURRENT/CopyOnWriteMap as one example (I believe that apache also has a copy when implementing a write map).

+1
source

synchronized methods or collections will certainly work. This is not the most effective approach, but it is easy to implement, and you will not notice the overhead if you do not get access to the structure millions of times per second.

Using a ConcurrentHashMap might be a better idea - it was designed for concurrency from the start and should work better in a very parallel situation.

0
source

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


All Articles