怎么证明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");
}
}