I have a spring based java app and my goal is to cache a bunch of objects in memory for performance and use a scheduled job to update that cache from the data source periodically.
If I am storing that map in a singleton spring bean, is there a thread safe way to update that map at runtime without making the access / service methods synchronous? Is it possible to do a temporary block of methods that are NOT synchronous on the singleton object while calling setMap(myNewMap)
? Is it necessary?
class MySingletonCache {
private Map<String, Object> myMap;
// Called periodically from scheduled job
public void setMap(Map<String, Object> myMap) {
this.myMap = myMap;
}
// High concurrency, cannot make this synchronous
public Object findById(String id) {
return this.myMap.get(id);
}
}
You can implement ReadWriteLock for this specific purpose.