I have an @ApplicationScoped bean for all users, that stores the ids-> names & vice versa in Trove & java.util maps.
I just build the maps once at construction of bean or (in case of manual refresh by the website admin).
Inside the bean methods, I am just using the get() with the maps, so not modifying the map. Is this going to be thread safe since it is used only for ready purposes? I am not sharing the maps with any other beans outside & not modifying the maps(adding/removing entries) anytime in my code.
Also, Is it neccesary in this case to make the fields final ?
Bean code as follows:
@ApplicationScoped
@ManagedBean(name="directory", eager=true)
public class directory {
private static TIntObjectHashMap<String> idsToNamesMap;
private static TreeMap<String, Integer> namesToIdsMap;
@PostConstruct
public void buildDirectory(){
// building directory here ....
}
public String getName(int topicId){
return idsToNamesMap.get(topicId);
}
public List<Entry<String, Integer>> searchTopicsByName(String query){
return new ArrayList(namesToIdsMap.subMap(query, true, query+"z", true).entrySet());
}
}
You don’t have to declare them volatile or protect with any kind of synchronization in this case. As long as the constructing thread will build them and synchronize with the main memory.
For that the constructing thread need just to make a single write to a volatile variable or enter/exit a synchronization lock. This will pass a memory barrier and all local thread data will be in the main thread. Then it will be safe for all other threads to read this data.
Even more – unnecessary volatile or synchronization block – costs a serious performance penalty – on each access to the variable it will pass the memory barrier – which is an expensive operation