ConcurrentHashMap和Hashtable put方法性能比较
ConcurrentHashMap和Hashtable put方法性能比较
测试代码说明:每次开启1000个线程,循环10次;
测试电脑运行的程序:idea、Google浏览器;
正常情况下电脑的cpu为5%;
public class Test {
public static void main(String[] args) throws InterruptedException {
List<Long> list = new ArrayList<>();
int count = 10;
int threads = 1000;
long sum = 0;
for (int i = 0; i < count; i++) {
Hashtable<Integer,Object> map = new Hashtable<>();
// ConcurrentHashMap<Integer,Object> map = new ConcurrentHashMap<>();
long l = test(map,threads);
list.add(l);
sum += l;
}
System.out.println(list);
Collections.sort(list);
System.out.println(list);
System.out.println("sum: "+sum+"; avg: "+(sum/count));
}
static long test(Map<Integer,Object> map,int threads)throws InterruptedException{
CountDownLatch countDownLatch = new CountDownLatch(threads);
AtomicLong atomicLong = new AtomicLong();
CyclicBarrier cyclicBarrier = new CyclicBarrier(threads,()-> atomicLong.set(System.currentTimeMillis()));
for (int i = 0; i < threads; i++) {
new Thread(new Run(i,countDownLatch,cyclicBarrier,map)).start();
}
countDownLatch.await();
return (System.currentTimeMillis()-atomicLong.get());
}
static class Run implements Runnable{
CountDownLatch countDownLatch;
CyclicBarrier cyclicBarrier;
int min;
int max;
Object obj = new Object();
Map<Integer,Object> map;
int factor = 10000;
public Run(int i, CountDownLatch countDownLatch, CyclicBarrier cyclicBarrier,Map<Integer,Object> map) {
this.countDownLatch = countDownLatch;
this.cyclicBarrier = cyclicBarrier;
this.max = (i+1)*factor;
this.min = i*factor;
this.map = map;
}
@Override
public void run() {
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
//代码1
for (int j = min; j < max; j++) {
map.put(j,obj);
}
//代码2
/*for (int j = 1; j < 100000; j++) {
map.put(j,obj);
}*/
countDownLatch.countDown();
}
}
}
代码1-结果
如下图:
由图可以看出:ConcurrentHashMap的平均执行时间要比Hashtable的大,每次的第一轮循环ConcurrentHashMap的耗时都是比较长,但是每一轮中ConcurrentHashMap的最小值,由极值和平均值可以看出ConcurrentHashMap数据样本的方差较大;
其他因素考虑:1、单纯测试put性能应该是每次都执行一次,即取上图结果中的第一条进行比较;ConcurrentHashMap最小值较小可能是jvm的优化技术(如:热点探测、本地化)造成的;
cpu情况:Hashtable:70%;ConcurrentHashMap:90%;
代码2-结果
如下图:
当key的竞争激烈时ConcurrentHashMap的性能明显较好,性能是Hashtable的3-4倍;
cpu情况:Hashtable:44%;ConcurrentHashMap:100%;