Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 更新地图并读取地图时无锁解决方案_Java_Database_Concurrency_Atomicity_Concurrenthashmap - Fatal编程技术网

Java 更新地图并读取地图时无锁解决方案

Java 更新地图并读取地图时无锁解决方案,java,database,concurrency,atomicity,concurrenthashmap,Java,Database,Concurrency,Atomicity,Concurrenthashmap,我试图测量每个线程插入数据库所需的时间。我已经在名为直方图的ConcurrentHashMap中捕获了所有这些性能数据,比如每个线程插入所花费的时间 下面是我用来测量每个线程花费多少时间并将其存储在ConcurrentHashMap class Task implements Runnable { public static ConcurrentHashMap<Long, AtomicLong> histogram = new ConcurrentHashMap<Long,

我试图测量每个线程插入数据库所需的时间。我已经在名为
直方图的
ConcurrentHashMap
中捕获了所有这些性能数据,比如每个线程插入所花费的时间

下面是我用来测量每个线程花费多少时间并将其存储在
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();
          }

         }
     }

    }

你的代码是正确的;还有一个(更复杂的)习惯用法,可以避免每次实例化
AtomicLong
。但是请注意,由于关键部分的持续时间很短,基于锁的“幼稚”解决方案可能也同样不错。

您可能有兴趣使用或,它会为您解决这一问题。
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);

     }

}