Search code examples
javamultithreadingconcurrenthashmap

Thread safe swap of entire map in Java


I'm implementing thread-safe map in the spring web service.

The map is such like this.

  • The map is read simultaneously in thousands of client threads.
  • The map's content has to be entirely updated sometimes(about once per hour).

I've chosen ConcurrentHashMap for thread-safe map, but there was no functionality to simply swap its content with newer one, like std::map::swap() in c++.
(I thought that atomic update of the entire content is required for multi-thread environment, maybe I'm wrong)

Is there an alternative map with swap?

Any suggestion or reply will be appreciated. Thanks.


Solution

  • If it isn't necessary to mutate the map, just atomically replacing it, you could wrap the map in an AtomicReference and atomically replace the reference in a single go. The different threads wouldn't keep a reference to the map instance itself, but the surrounding AtomicReference instance.

    class Example {
        private final AtomicReference<Map<String, String>> mapRef = new AtomicReference<>(someInitialState);
    
        private void consumerThread() {
            // Get the current version of the map and look up a value from it.
            String value = mapRef.get().get("Hello");
            // Do something with value.
        }
    
        private void producerThread() {
            // Time to replace the whole map for all threads
            Map<String, String> newMap = calculateNewMap();
            mapRef.set(newMap);
        }
    }