存储在ConcurrentHashMap中的原子递增计数器 [英] Atomically incrementing counters stored in ConcurrentHashMap

查看:546
本文介绍了存储在ConcurrentHashMap中的原子递增计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网路应用程式的各个地方收集一些指标。为了保持简单,所有这些都将是计数器,因此唯一的修改操作是将它们递增1.

I would like to collect some metrics from various places in a web app. To keep it simple, all these will be counters and therefore the only modifier operation is to increment them by 1.

增量将是并发的和经常的。读取(转储统计信息)是一个罕见的操作。

The increments will be concurrent and often. The reads (dumping the stats) is a rare operation.

我想使用ConcurrentHashMap。问题是如何正确增量计数器。由于地图没有增量操作,我需要先读取当前值,增加它,而不是在地图中放置新值。没有更多的代码,这不是一个原子操作。

I was thinking to use a ConcurrentHashMap. The issue is how to increment the counters correctly. Since the map doesn't have an "increment" operation, I need to read the current value first, increment it than put the new value in the map. Without more code, this is not an atomic operation.

是否可以实现这个没有同步(这将失去ConcurrentHashMap的目的)?我需要查看 Google Collections 吗?

Is it possible to achieve this without synchronization (which would defeat the purpose of the ConcurrentHashMap)? Do I need to look at Google Collections ?

感谢任何指针。

PS有一个与SO相关的问题(在Java中增加Map值的最有效的方法)但是注重性能而不是多线程

PS There is a related question on SO (Most efficient way to increment a Map value in Java) but focused on performance and not multi-threading

编辑:对于通过对同一主题搜索到达的用户:除了以下答案,还有一个有用的演示文稿,其偶然涉及相同的主题。见幻灯片24-33。

For those arriving here through searches on the same topic: besides the answers below, there's a useful presentation which incidentally covers the same topic. See slides 24-33.

推荐答案

在Java 8中:

ConcurrentHashMap<String, LongAdder> map = new ConcurrentHashMap<>();

map.computeIfAbsent("key", k -> new LongAdder()).increment();

这篇关于存储在ConcurrentHashMap中的原子递增计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆