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);
}
}