【Java多线程系列六】Map实现类
2024-10-07 18:13:08
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 |
以下代码测试各类的读写效率:
package com.concurrent.test; 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; /**
* 测试map
*/
public class ThreadMapTest { public static void main(String[] args) throws InterruptedException {
Map<Integer, Integer> hashtable = new Hashtable<>();
Map<Integer, Integer> hashmap = new HashMap<>();
Map<Integer, Integer> synchronizedHashMap = Collections.synchronizedMap(new HashMap<Integer, Integer>());
Map<Integer, Integer> concurrentHashMap = new ConcurrentHashMap<>(); test(hashtable);
test(hashmap);
test(synchronizedHashMap);
test(concurrentHashMap);
} private static void test(Map<Integer, Integer> 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(final Map<Integer, Integer> 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 < 50000; j++) {
map.put(0, 0);
map.get(0);
}
}
}); }
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
return System.currentTimeMillis() - startMillis;
} }
输出结果如下:
Test class java.util.Hashtable average time 104
Test class java.util.HashMap average time 31
Test class java.util.Collections$SynchronizedMap average time 79
Test class java.util.concurrent.ConcurrentHashMap average time 66
最新文章
- Parameter Passing / Request Parameters in JSF 2.0 (转)
- 不引用office动态库导出excel
- xcode6 使用MJRefresh
- kafka安装与使用
- 磁珠(FB)的原理
- 内核空间和用户空间的分界 PAGE_OFFSET
- BZOJ 3924: [Zjoi2015]幻想乡战略游戏(动态点分治)
- CF #228 div1 B. Fox and Minimal path
- ElasticSearch 插件jdbc import(1)-----定时执行
- ubuntu实时显示网速cpu占用和内存占用率
- MFC 中线程传递CString 是不安全的 转
- ios WKWebView 与 JS 交互实战技巧
- 深度理解 React Suspense(附源码解析)
- Centos防火墙设置与端口开放的方法
- JAVA项目中的常用的异常处理
- 笔记 Bioinformatics Algorithms Chapter7
- android 获取 imei号码
- 初识Identity并添加身份验证管理页面
- ZBar与ZXing使用后感觉
- 【Ubuntu】Windows硬盘安装Ubuntu14.04