ConcurrentHashMap与synchronizedMap比较分析

synchronizedMap类采用装饰器模式,通过synchronized关键字将原有的Map类(如HashMap)方法进行同步,保证了多线程情况在访问该同步类时的串行化,从而保证了线程安全。这种方式实现较为简单,但是可伸缩性较低,当多个线程同时请求访问该同步容器类的对象时,效率较低。

ConcurrentHashMap类是为实现高并发而设计的类,它采用了分段锁的设计,从而使得多个线程在访问该Map的不同段的Entry时可以获取不同的锁,从而提高了伸缩性,效率相对同步容器类高。

public class ConcurrentHashMapTest {

	static Object obj = new Object();
	static Map map1 = new ConcurrentHashMap();
	static Map map2 = Collections.synchronizedMap(new HashMap());

	public static void main(String[] args) throws InterruptedException {
		final int threadNum = 5;
		Thread[] ts1 = new Thread[threadNum];
		Thread[] ts2 = new Thread[threadNum];
		for (int i = 0; i < threadNum; i++) {
			Thread t1 = new Thread() {
				@Override
				public void run() {
					for (int i = 0; i < 999999; i++) {
						map1.put(new Object(), obj);
					}
				}
			};
			ts1[i] = t1;
			Thread t2 = new Thread() {
				@Override
				public void run() {
					for (int i = 0; i < 999999; i++) {
						map2.put(new Object(), obj);
					}
				}
			};
			ts2[i] = t2;
		}
		computeTime(ts1, "ConcurrentHashMap");
		computeTime(ts2, "synchronizedMap");
	}

	public static void computeTime(Thread[] ts, String mapName) throws InterruptedException {
		long begin2 = System.currentTimeMillis();
		for (Thread t : ts) {
			t.start();
		}
		for (Thread t : ts) {
			t.join();
		}
		System.out.println(mapName + "总共耗时:" + (System.currentTimeMillis() - begin2));
	}
}

结果:

ConcurrentHashMap总共耗时:1300
synchronizedMap总共耗时:2161


你可能感兴趣的:(java并发)