The ReadWriteLock javadoc at Oracle and its implementation describe what the lock does and how to use it but doesn't say anything about whether to use the volatile
keyword.
This is not the same question as do-all-mutable-variables-need-to-be-volatile-when-using-locks because I'm happy that the lock will synchronise access and visibility properly, but is the use of volatile
for the variables still a good idea, e.g. for compiler optimisations or any other reasons?
My cached data consists of a rarely changed List
and several Maps
mapping the objects in the list using various attributes of the objects.
private void reload() {
Set<Registration> newBeans = dao.listRegistered();
beans = Collections.unmodifiableSet(newBeans);
codeToBeanMap.clear();
userToBeanMap.clear();
nameToBeanMap.clear();
idToBeanMap.clear();
for (Registration bean : newBeans) {
codeToBeanMap.put(bean.getCode(), bean);
userToBeanMap.put(bean.getUser(), bean);
nameToBeanMap.put(bean.getName(), bean);
idToBeanMap.put(bean.getId(), bean);
}
}
What would be the best declarations? I have this:
private Set<Registration> ecns;
private final Map<String, Registration> codeToBeanMap =
new HashMap<String, Registration>();
private final Map<String, Registration> userToBeanMap =
new HashMap<String, Registration>();
private final Map<String, Registration> nameToBeanMap =
new HashMap<String, Registration>();
private final Map<String, Registration> idToBeanMap =
new HashMap<String, Registration>();