I am writing a web-service that heavily relies on a single large Map that is completely updated once every hour. The rest of the time many threads concurrently read the table.
My question is: What is the most efficient construct to realize such a Map?
The Map can be rather larger (100 - 500 MB). There is only read access except once an hour where the whole map is replaced.
I was thinking about just using a Java HashMap and maybe using reflection to set the field final between the updates if this improves performance, but I have no clue how to make the JVM optimize for many concurrent reads.
Since the map isn't updated while being used, use a HashMap
, which gives excellent O(1) lookup performance (at the sacrifice of thread safety).
When it's time to refresh, build a new map and swap references.
Consider using an AtomicReference
to make the swap thread safe:
private final AtomicReference<Map<K, V>> mapRef = new AtomicReference<>();
To use:
mapRef.get().get(key);
To initialize or swap in a new map:
Map<K, V> newMap = new HashMap<>();
// populate map
mapRef.set(newMap); // all threads will see this change
Go for ConcurrentHashMap. It allows Concurrent read access without compromising on performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With