I’m having a Map object that could be null or simply cleared when the application first starts. I need all threads accessing this map to block till the map is initialized and only then I need to signal all threads to access this map.
This map holds configuration data and it will be for reading only unless a single threads decides to refresh to load new configuration data (So it doesn’t need to Synchronized for the sake of performance as I don’t find necessary too). I tried using a Condition object for a ReentrantLock but it threw IllegalMonitorState exceptions whenever I tried to signalAll() or await().
Here is a pseudo code for what I need to do:
void monitorThread{
while(someCondition){
map = updatedMap();
condition.signalAll();
}
}
String readValueFromMap(String key){
if(map == null){
condition.await();
}
return map.get(key);
}
To do this right, you need a memory barrier hence the
volatile. Because the map may be null initially, you are going to need another lock object. The following should work: