java的map多线程_Java多线程系列六——Map实现类

本文探讨了Java中几种Map实现类的线程安全性和性能特性,包括Hashtable、HashMap、Collections.synchronizedMap及ConcurrentHashMap。HashMap在多线程环境下可能导致死循环,而ConcurrentHashMap通过分段锁提供了高效且线程安全的选择。文章通过测试展示了它们的读写效率差异。
摘要由CSDN通过智能技术生成

参考资料:

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/

https://stackoverflow.com/questions/35534906/java-hashmap-getobject-infinite-loop

Map的一些实现类有及其特性

线程安全

特性

Hashtable

Key不能为null

HashMap

读写效率最高,但在Java6多线程环境下使用不当可能陷入死循环,进而导致CPU使用率过高(原理可参见:http://coolshell.cn/articles/9606.html)

Collections.synchronizedMap

Collections.SynchronizedMap在Map所有方法基础上加锁,效率与HashTable相当

ConcurrentHashMap

采用分段锁,get一般不加锁,put分段锁,key/value不能为null,效率仅次于HashMap

以下代码测试各类的读写效率

a9a62dcf6c3179da0354f4ca3dc90455.gif

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;

/**

* @Description: 测试map

*/

public class ThreadMapTest {

public static void main(String[] args) throws InterruptedException {

Map hashtable = new Hashtable<>();

Map hashmap = new HashMap<>();

Map synchronizedHashMap = Collections.synchronizedMap(new HashMap<>());

Map concurrentHashMap = new ConcurrentHashMap<>();

test(hashtable);

test(hashmap);

test(synchronizedHashMap);

test(concurrentHashMap);

}

private static void test(Map map) throws InterruptedException {

int testTimes = 5;

long totalTimeMillis = 0;

for (int k = 0; k < testTimes; k++) {

totalTimeMillis += costTimeMillis(map);

}

System.out.println("Test " + map.getClass() + " average time " + (totalTimeMillis / testTimes));

}

private static long costTimeMillis(Map map) throws InterruptedException {

int count = 5;

ExecutorService executorService = Executors.newFixedThreadPool(count);

long startMillis = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

executorService.execute(new Runnable() {

@Override

public void run() {

for (int j = 0; j < 500000; j++) {

map.put(0, 0);

map.get(0);

}

}

});

}

executorService.shutdown();

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

return System.currentTimeMillis() - startMillis;

}

}

a9a62dcf6c3179da0354f4ca3dc90455.gif

输出结果如下:

Test class java.util.Hashtable average time 267

Test class java.util.HashMap average time 67

Test class java.util.Collections$SynchronizedMap average time 262

Test class java.util.concurrent.ConcurrentHashMap average time 167

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值