I intend to create a realtime counter. So one user can incremenet the counter value for specific key. Whilst another gets the updated count value via an ajax request (either in a loop, or using some long polling method). I will use a spring controller, which will inject the service class can I do something like below, or is there a better way :
@Service
public MyService{
//instance variable in spring injected service class, not sure if this correct
static final Map<String, Integer> myMap;
public void add(String key){
Integer count = myMap.get(key);
count++;
myMap.put(key, count);
}
//accessed via ajax loop (and controller), if value changes update display
public Integer getCount(String key){
return myMap.get(key)
}
@PostConstruct
public load(){
myMap = new HashMap<String, Integer>(10){{//initialize}};
}
Edit there are a few answers but it is not clear which is the best : Synchronize the add method ? Create map in another class(annotated repository) and inject that ? Something else ?
You can, but need to be aware of those problems: