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?
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.
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:
getNewValues
does not need to be synchronized or atomicmap
is atomicmap
is volatile, which guarantees that other threads will see the changeIf 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