我正在尝试在注入控制器的单例弹簧服务中实现 ConcurentHashMap 的线程安全使用:
@Service
public MyService{
final ConcurrentMap<String, AtomicInteger> myMap = new ConcurrentHashMap<String, AtomicInteger>(10) {
{/* initialize the ten key/values */
}
};
public int add(String key) {
return myMap.get(key).incrementAndGet();
}
// accessed via ajax loop (and controller), if value changes update display
public int getCount(String key) {
return myMap.get(key).get();
}
}
有没有更好的方法来访问 hashmap 线程安全?我怎样才能使它适应在集群环境中工作?这是对我的另一个问题的跟进。