java - 更新 map 并阅读时锁定免费解决方案

标签 java database concurrency atomic concurrenthashmap

我正在尝试测量每个线程插入数据库所需的时间。我在 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/

相关文章:

java - String.split() 导致创建空字符串,如何防止这种情况?

node.js - 删除方法在 MongoDB 中不起作用。每当我删除凭证时,我都会收到 CastError

mysql - 如何在规范化数据库中加入 tag_map

java - 生产者-消费者队列能够将项目移到前面

python - 将多个参数传递给 concurrent.futures.Executor.map?

java - java中多个for内部的计时方法

java - JSP:在文件上传时获取 MIME 类型

java - 服务器配置问题

mysql - 如何编写此查询以正确过滤结果?

haskell - 为什么 Haskell 中没有隐式并行性?