我正在尝试测量每个线程插入数据库所需的时间。我在 ConcurrentHashMap
中捕获了所有这些性能数据。命名histogram
比如每个线程插入花费的时间。
下面是我测量每个线程花费的时间并将其存储在 ConcurrentHashMap
中的代码。
class Task implements Runnable {
public static ConcurrentHashMap<Long, AtomicLong> histogram = new ConcurrentHashMap<Long, AtomicLong>();
@Override
public void run() {
try {
long start = System.nanoTime();
preparedStatement.executeUpdate(); // flush the records.
long end = System.nanoTime() - start;
final AtomicLong before = histogram.putIfAbsent(end / 1000000, new AtomicLong(1L));
if (before != null) {
before.incrementAndGet();
}
}
}
}
所以我的问题是我是否试图测量每个线程花费多少时间并将所有这些数字存储在 ConcurrentHashMap
中线程安全与否?
我认为我的整个更新操作是 Atomic
。我只是想看看如果我的整个操作不是 Atomic
是否有比这更好的方法。我主要寻找lock free solution
.
然后在每个线程完成执行任务后,我打印这个 Histogram
从 main 方法进行映射,因为我将该映射设置为 Static
。那么这种方式到底对不对呢?
public class LoadTest {
public static void main(String[] args) {
//executing all the threads using ExecutorService
//And then I am printing out the historgram that got created in Task class
System.out.println(Task.histogram);
}
}
最佳答案
您的代码是正确的;还有一种(更复杂的)习惯用法可以避免每次实例化 AtomicLong
。但请注意,由于关键部分的持续时间非常短,“天真的”基于锁的解决方案可能同样好。
关于java - 更新 map 并阅读时锁定免费解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780797/