【发布时间】:2023-03-28 01:02:01
【问题描述】:
我正在开发一个metric store(Map),它主要收集一些操作的metrics,比如
- 混合
- 最大
- 计数器
- timeElapsed[] 等
这里的 Key 是方法的名称,value 是关于它的指标。
Spring 可以帮助我创建 MetricStore 的单例对象,我正在使用 ConcurrentHashMap 来避免 多个 REST 请求并行时出现竞争条件。
我的查询 1- 我需要使 MetricStore 变量存储易失吗?提高多个请求之间的可见性。 2-我使用 Map 作为基类,使用 ConcurrentHashMap 作为实现,它是否会影响 Map 不是 ThreadSafe。 -
@Component
class MetricStore{
public Map<String, Metric> store = new ConcurrentHashMap<>();
//OR public volatile Map<String, Metric> store = new ConcurrentHashMap<>();
}
@RestController
class MetricController{
@Autowired
private MetricStore metricStore;
@PostMapping(name="put")
public void putData(String key, Metric metricData) {
if(metricStore.store.containsKey(key)) {
// udpate data
}
else {
metricStore.store.put(key, metricData);
}
}
@PostMapping(name="remove")
public void removeData(String key) {
if(metricStore.store.containsKey(key)) {
metricStore.store.remove(key);
}
}
}
【问题讨论】:
-
re: "Map is not ThreadSafe" – java.util.Map 不是线程安全或非线程安全的,它只是一些底层实现的接口。
-
感谢@kaan 的评论
标签: java spring multithreading thread-safety concurrenthashmap