Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap vs ReentrantReadWriteLock based Custom Map for Reloading

Java Gurus,

Currently we have a HashMap<String,SomeApplicationObject> which is being read frequently and modified occasionally and we are having issues that during the modification/reloading, Read operation returns null which is not acceptable.

To fix this I have following options:

A. Use ConcurrentHashMap

Which looks like the first choice but the operation which we are talking about is reload() - means clear() followed by replaceAll(). So if the Map is read post clear() and pre replaceAll() it returns null which is not desirable. Even if I synchronize this doesn't resolves the issue.

B. Create another implementation based upon ReentrantReadWriteLock

Where I would create acquire Write Lock before reload() operation. This seems more appropriate but I feel there must be something already available for this and I need not to reinvent the wheel.

What is the best way out?

EDIT Is any Collection already available with such feature?

like image 955
Bharat Sinha Avatar asked Aug 24 '12 12:08

Bharat Sinha


2 Answers

Since you are reloading the map, I would replace it on a reload.

You can do this by using a volatile Map, which you replace in full when it is updated.

like image 86
Peter Lawrey Avatar answered Oct 27 '22 13:10

Peter Lawrey


It seems you are not sure as to how what Peter Lawrey suggests can be implemented. It could look like this:

class YourClass {
    private volatile Map<String, SomeApplicationObject> map;

    //constructors etc.

    public void reload() {
        Map<String,SomeApplicationObject> newMap = getNewValues();
        map = Collections.unmodifiableMap(newMap);
    }
}

There are no concurrency issues because:

  • The new map is created via a local variable, which by definition is not shared - getNewValues does not need to be synchronized or atomic
  • The assignement to map is atomic
  • map is volatile, which guarantees that other threads will see the change
like image 38
assylias Avatar answered Oct 27 '22 13:10

assylias