I need to store a lookup map in memory on a servlet. The map should be loaded from a file, and whenever the file is updated (which is not very often), the map should be reloaded in the same thread that is doing the lookup.
But I'm not sure how to implement this functionality in a thread safe manner. I want to make sure that the reload does not happen more than once.
public class LookupTable
{
private File file;
private long mapLastUpdate;
private Map<String, String> map;
public String getValue(String key)
{
long fileLastUpdate = file.lastModified();
if (fileLastUpdate > mapLastUpdate)
{
// Only the first thread should run the code in the synchronized block.
// The other threads will wait until it is finished. Then skip it.
synchronized (this)
{
Map newMap = loadMap();
this.map = newMap;
this.mapLastUpdate = fileLastUpdate;
}
}
return map.get(key);
}
private Map<String, String> loadMap()
{
// Load map from file.
return null;
}
}
If anyone has any suggestions on external libraries that has solved this already, that would work too. I took a quick look at some caching libraries, but I couldn't find what I needed.
Thanks