比较方法:各启5个线程,每个线程里面操作50w的数据,最后5个线程算平均时间,即为某一个实现类的执行时间
/**
*
* 比较Hashtable、synchronizedMap、ConcurrentHashMap的速度
* 各启5个线程,每个线程里面操作50W的数据,最后5个线程算平均时间,即为某一个实现类的执行时间
*/
public class TestSpeed {
public final static int THREAD_POOL_SIZE = 5;
public static Map<String, Integer> map = null;
public static void main(String[] args) {
map = new Hashtable<>();
crunchifyPerformTest(map);
System.out.println("********************************");
map = Collections.synchronizedMap(new HashMap<String, Integer>());
crunchifyPerformTest(map);
System.out.println("********************************");
map = new ConcurrentHashMap<>();
crunchifyPerformTest(map);
}
private static void crunchifyPerformTest(Map<String, Integer> map) {
System.out.println("Test started for:" + map.getClass());
long averageTime = 0;
for (int i = 0; i < 5; i++) {
long startTime = System.currentTimeMillis();
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
for (int j = 0; j < THREAD_POOL_SIZE; j++) {
executorService.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 500000; i++) {
Integer crunchifyRandomNumber = (int)Math.ceil(Math.random()*550000);
map.put(String.valueOf(crunchifyRandomNumber), crunchifyRandomNumber);
}
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime-startTime;
averageTime += totalTime;
System.out.println("totalTime:" + totalTime + "ms");
}
System.out.println("For " + map.getClass() + " the average time is " + averageTime/5 + "ms");
}
}
运行结果:
Test started for:class java.util.Hashtable
totalTime:2272ms
totalTime:1669ms
totalTime:1296ms
totalTime:1166ms
totalTime:1145ms
For class java.util.Hashtable the average time is 1509ms
********************************
Test started for:class java.util.Collections$SynchronizedMap
totalTime:1307ms
totalTime:1194ms
totalTime:1097ms
totalTime:1181ms
totalTime:1585ms
For class java.util.Collections$SynchronizedMap the average time is 1272ms
********************************
Test started for:class java.util.concurrent.ConcurrentHashMap
totalTime:638ms
totalTime:697ms
totalTime:644ms
totalTime:553ms
totalTime:639ms
For class java.util.concurrent.ConcurrentHashMap the average time is 634ms
由结果可以看出ConcurrentHashMap速度是最快的