5

I have a hashmap which stores around 1 G of data is terms of key value pairs. This hashmap changes every 15 days. It will be loaded into memory and used from there.

When a new hashmap has to be loaded into the memory, there would be several transactions already accessing the hashmap in memory. How can I replace the old hashmap with the new one without effecting the current transactions accessing the old hashmap. If there a way to hot swap the hashmap in memory?

Abhi
  • 129
  • 6

3 Answers3

3

Use an AtomicReference<Map<Foo, Bar>> rather than exposing a direct (hard) reference to the map. Consumers of the map will use #get(), and when you're ready to swap out the map, your "internal" code will use #set() or #getAndSet().

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1
  1. Provide a getter to the map
  2. Mark the map private and volatile
  3. When updating the map, create a new one, populate it and when it is ready, assign it to your private map variable.

Reference assignments are atomic in Java and volatile ensures visibility.

Caveats:

  • you will have two maps in memory at some stage
  • if some code keeps a reference to the old map it will access stale data. If that is an issue you can completely hide the map and provide a get(K key) instead so that users always access the latest map.
assylias
  • 321,522
  • 82
  • 660
  • 783
0

I will suggest to use caching tools like memcached if the data size is large like yours. This way you can invalidate individual items or entire cache as per your requirement.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55