HashMap和SynchronizedMap和ConcurrentHashMap性能比较

怎么证明HashMap和SynchronizedMap和ConcurrentHashMap性能优劣


代码如下:

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class HashTableVsSynchronizedMapVsConcurrentHashMap {
	public final static int THREAD_POOL_SIZE = 5;
	
	public static Map<String, Integer> hashTableObject = null;
	public static Map<String, Integer> synchronizedMapObject = null;
	public static Map<String, Integer> concurrentHashMapObject = null;
	
	public static void main(String[] args) throws InterruptedException {
		// 测试HashTable
		hashTableObject = new Hashtable<String, Integer>();
		performTest(hashTableObject);
		
		// 测试synchronizedMap
		synchronizedMapObject = Collections.synchronizedMap(new HashMap<String, Integer>());
		performTest(synchronizedMapObject);

        // 测试ConcurrentHashMap
        concurrentHashMapObject = new ConcurrentHashMap<String, Integer>();
        performTest(concurrentHashMapObject);
        
	}

	private static void performTest(final Map<String, Integer> map) throws InterruptedException {
		System.err.println("开始测试 : " + map.getClass());
		long averageTime = 0;
		for (int i = 0; i < 5; i++) {
			long startTime = System.nanoTime();
			ExecutorService es = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
			for (int j = 0; j < THREAD_POOL_SIZE; j++) {
				es.execute(new Runnable() {
					@Override
					public void run() {
						for (int i = 0; i < 500000; i++) {
							Integer randomNumber = (int) Math.ceil(Math.random() * 550000);
							map.put(String.valueOf(randomNumber), randomNumber);
						}
					}
				});
			}
			
			es.shutdown();

			es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

			long entTime = System.nanoTime();
			long totalTime = (entTime - startTime) / 1000000L;
			averageTime += totalTime;
			System.out.println("添加耗时" + totalTime + " ms");
		}
		System.out.println("操作 " + map.getClass() + " 平均时间为 " + averageTime / 5 + " ms\n");
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值