HashMap和ConcurrentHashMap的并发性能测试
(2011-04-15 21:55:08)
标签:
hashmapconcurrent并发性能测试it |
分类: JAVA |
先看看代码吧,模拟1000个并发,每个测试1000次操作,循环测试10轮。分别测试Put和Get操作
-
import
java.util.Collections; - import
java.util.HashMap; -
import
java.util.Hashtable; - import
java.util.Map; -
import
java.util.concurrent.ConcurrentHashMap; -
public
class T { -
final int threads 1000;= -
final int NUMBER 1000;= -
static void main(String[] throwsargs) Exception { -
Map<String, Integer> hashmapSync = Collections -
.synchronizedMap( HashMap<String, Integer>());//同步的hashmap -
Map<String, Integer> concurrentHashMap = ConcurrentHashMap<String, Integer>(); -
Map<String, Integer> hashtable = Hashtable<String, Integer>(); -
totalA 0;= -
totalB 0;= -
totalC 0;= -
( inti 0;= i 10;<= i++) { -
totalA += testPut(hashmapSync); -
totalB += testPut(concurrentHashMap); -
totalC += testPut(hashtable); -
} -
System.out.println( time HashMapSync=" + "ms.");totalA + -
System.out.println( time ConcurrentHashMap=" + "ms.");totalB + -
System.out.println( time Hashtable=" + "ms.");totalC + -
totalA = -
totalB = -
totalC = -
( inti 0;= i 10;<= i++) { -
totalA += testGet(hashmapSync); -
totalB += testGet(concurrentHashMap); -
totalC += testGet(hashtable); -
} -
System.out.println( time HashMapSync=" + "ms.");totalA + -
System.out.println( time ConcurrentHashMap=" + "ms.");totalB + -
System.out.println( time Hashtable=" + "ms.");totalC + -
} -
static long testPut(Map<String, throwsInteger> map) Exception { -
start = System.currentTimeMillis(); -
( inti 0;= i < threads; i++) { -
MapPutThread(map).start(); -
} -
(MapPutThread.counter 0)> { -
Thread.sleep( -
} -
System.currentTimeMillis() - start; -
} -
static long testGet(Map<String, throwsInteger> map) Exception { -
start = System.currentTimeMillis(); -
( inti 0;= i < threads; i++) { -
MapPutThread(map).start(); -
} -
(MapPutThread.counter 0)> { -
Thread.sleep( -
} -
System.currentTimeMillis() - start; -
} - }
-
class
MapPutThread extendsThread { -
int counter 0;= -
Object newlock = Object(); -
Map<String, Integer> map; -
String this.getId()key = + ""; -
MapPutThread(Map<String, Integer> map) { -
(lock) { -
counter++; -
} -
= map; -
} -
void run() { -
( inti 1;= i <= T.NUMBER; i++) { -
map.put(key, i); -
} -
(lock) { -
counter--; -
} -
} - }
-
class
MapGetThread extendsThread { -
int counter 0;= -
Object newlock = Object(); -
Map<String, Integer> map; -
String this.getId()key = + ""; -
MapGetThread(Map<String, Integer> map) { -
(lock) { -
counter++; -
} -
= map; -
} -
void run() { -
( inti 1;= i <= T.NUMBER; i++) { -
map.get(key); -
} -
(lock) { -
counter--; -
} -
} - }
运行结果:
Put time HashMapSync=3966ms.
Put time ConcurrentHashMap=1892ms.
Put time Hashtable=3892ms.
Get time HashMapSync=3812ms.
Get time ConcurrentHashMap=1828ms.
Get time Hashtable=3985ms.
结论:
ConcurrentHashMap的性能比同步的HashMap快一倍左右
同步的HashMap和Hashtable的性能相当
转自:http://blog.csdn.net/java2000_net/archive/2008/11/25/3373181.aspx