2008-02-24
Map 四种同步方式的性能比较
如果需要使 Map 线程安全,大致有这么四种方法:
1、使用 synchronized 关键字,这也是最原始的方法。代码如下
JDK1.2 提供了 Collections.synchronizedMap(originMap) 方法,同步方式其实和上面这段代码相同。
2、使用 JDK1.5 提供的锁(java.util.concurrent.locks.Lock)。代码如下
3、实际应用中,可能多数操作都是读操作,写操作较少。针对这种情况,可以使用 JDK1.5 提供的读写锁(java.util.concurrent.locks.ReadWriteLock)。代码如下
这样两个读操作可以同时进行,理论上效率会比方法 2 高。
4、使用 JDK1.5 提供的 java.util.concurrent.ConcurrentHashMap 类。该类将 Map 的存储空间分为若干块,每块拥有自己的锁,大大减少了多个线程争夺同一个锁的情况。代码如下
写了段测试代码,针对这四种方式进行测试,结果见附图。测试内容为 1 秒钟所有 get 方法调用次数的总和。为了比较,增加了未使用任何同步机制的情况(非安全!)。理论上,不同步应该最快。
我的 CPU 是双核的(Core 2 Duo E6300),因此太多线程也没啥意义,所以只列出了单线程、两个线程和五个线程的情况。更多线程时,CPU 利用率提高,但增加了线程调度的开销,测试结果与五个线程差不多。
从附图可以看出:
1、不同步确实最快,与预期一致。
2、四种同步方式中,ConcurrentHashMap 是最快的,接近不同步的情况。
3、synchronized 关键字非常慢,比使用锁慢了两个数量级。真是大跌眼镜,我很迷惑为什会 synchronized 慢到这个程度。
4、使用读写锁的读锁,比普通所稍慢。这个比较意外,可能硬件或测试代码没有发挥出读锁的全部功效。
结论:
1、如果 ConcurrentHashMap 够用,则使用 ConcurrentHashMap。
2、如果需自己实现同步,则使用 JDK1.5 提供的锁机制,避免使用 synchronized 关键字。
1、使用 synchronized 关键字,这也是最原始的方法。代码如下
synchronized(anObject)
{
value = map.get(key);
}
JDK1.2 提供了 Collections.synchronizedMap(originMap) 方法,同步方式其实和上面这段代码相同。
2、使用 JDK1.5 提供的锁(java.util.concurrent.locks.Lock)。代码如下
lock.lock(); value = map.get(key); lock.unlock();
3、实际应用中,可能多数操作都是读操作,写操作较少。针对这种情况,可以使用 JDK1.5 提供的读写锁(java.util.concurrent.locks.ReadWriteLock)。代码如下
rwlock.readLock().lock(); value = map.get(key); rwlock.readLock().unlock();
这样两个读操作可以同时进行,理论上效率会比方法 2 高。
4、使用 JDK1.5 提供的 java.util.concurrent.ConcurrentHashMap 类。该类将 Map 的存储空间分为若干块,每块拥有自己的锁,大大减少了多个线程争夺同一个锁的情况。代码如下
value = map.get(key); //同步机制内置在 get 方法中
写了段测试代码,针对这四种方式进行测试,结果见附图。测试内容为 1 秒钟所有 get 方法调用次数的总和。为了比较,增加了未使用任何同步机制的情况(非安全!)。理论上,不同步应该最快。
我的 CPU 是双核的(Core 2 Duo E6300),因此太多线程也没啥意义,所以只列出了单线程、两个线程和五个线程的情况。更多线程时,CPU 利用率提高,但增加了线程调度的开销,测试结果与五个线程差不多。
从附图可以看出:
1、不同步确实最快,与预期一致。
2、四种同步方式中,ConcurrentHashMap 是最快的,接近不同步的情况。
3、synchronized 关键字非常慢,比使用锁慢了两个数量级。真是大跌眼镜,我很迷惑为什会 synchronized 慢到这个程度。
4、使用读写锁的读锁,比普通所稍慢。这个比较意外,可能硬件或测试代码没有发挥出读锁的全部功效。
结论:
1、如果 ConcurrentHashMap 够用,则使用 ConcurrentHashMap。
2、如果需自己实现同步,则使用 JDK1.5 提供的锁机制,避免使用 synchronized 关键字。
评论
qiuyuanshan
2008-04-22
看楼主的图很吓人,synchronized效率这么差啊,jdk1.4的也只能用这个了吧
网上有人建议是说建一个
final static Object lockForMap=new Object();
然后
synchronized(lockForMap){
value=map.get(key);
}
因为synchronized(map)的话,有可能map会被重新实例化,这样子也不保险。
网上有人建议是说建一个
final static Object lockForMap=new Object();
然后
synchronized(lockForMap){
value=map.get(key);
}
因为synchronized(map)的话,有可能map会被重新实例化,这样子也不保险。
dagzhao
2008-03-08
jomper 写道
上面的评论相当的精彩
我请教一下为什么不是
我请教一下为什么不是
synchronized(map){
value = map.get(key);
}其实是一样的,
synchronized(anObject)
{
value = map.get(key);
}
synchronized(map){
value = map.get(key);
}
如果anObject只用在map的get和put的同步中,效果是一样的;
jomper
2008-03-05
上面的评论相当的精彩
我请教一下为什么不是
我请教一下为什么不是
synchronized(map){
value = map.get(key);
}
jsyx
2008-02-27
cammette 写道
jsyx 写道
cammette 写道
jsyx 写道
cammette 写道
第一种这样会好点
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
value = map.get(key);
}
个人认为,这种写法不是线程安全的
为什么呢?
我们操作map时关注的是key对应的value。
只要我们改变某key的value能同步不就可以了吗?
你总要考虑到写的情况吧。
楼主的测试使用的是HashMap。
在java中,hashmap内部是使用数组来实现的。
无论是put还是get,首先都要根据key的hash值以及数组的长度以及一些其他的常数,计算出一个位置,然后对应get/put,会在这个位置内搜寻或者放置value。当map中存入的对象的个数到了一个临界值时(threshold),hashmap会重新初始化一个新的更长的数组,并且会重新分配所有已存的对象。
public V get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry<K,V> e = table[i];
while (true) {
if (e == null)
return null;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
public V put(K key, V value) {
K k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
if (e.hash == hash && eq(k, e.key)) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, k, value, i);
return null;
}
举例来说:
如果你只同步key,那么当执行到这一行,以后
int i = indexFor(hash, table.length);
另外一个线程执行了一个新的put操作,导致数组被resize,对象被重新放置。
这样的结果就是你的get操作取不出正确的value或者直接返回null
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
受教了。
不过lz的
synchronized(anObject)
{
value = map.get(key);
} 也会遇到这个问题
synchronized(anObject)
{
value = map.get(key);
}
synchronized(anObject)
{
map.put(key, value);
}
这样,我觉得不会有问题,只要保证put和get都同步到这个anObject上来
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
map.put(key, value);
}
这样会有问题,因为put和get的key可能是不同的对象
cammette
2008-02-27
jsyx 写道
cammette 写道
jsyx 写道
cammette 写道
第一种这样会好点
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
value = map.get(key);
}
个人认为,这种写法不是线程安全的
为什么呢?
我们操作map时关注的是key对应的value。
只要我们改变某key的value能同步不就可以了吗?
你总要考虑到写的情况吧。
楼主的测试使用的是HashMap。
在java中,hashmap内部是使用数组来实现的。
无论是put还是get,首先都要根据key的hash值以及数组的长度以及一些其他的常数,计算出一个位置,然后对应get/put,会在这个位置内搜寻或者放置value。当map中存入的对象的个数到了一个临界值时(threshold),hashmap会重新初始化一个新的更长的数组,并且会重新分配所有已存的对象。
public V get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry<K,V> e = table[i];
while (true) {
if (e == null)
return null;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
public V put(K key, V value) {
K k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
if (e.hash == hash && eq(k, e.key)) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, k, value, i);
return null;
}
举例来说:
如果你只同步key,那么当执行到这一行,以后
int i = indexFor(hash, table.length);
另外一个线程执行了一个新的put操作,导致数组被resize,对象被重新放置。
这样的结果就是你的get操作取不出正确的value或者直接返回null
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
受教了。
不过lz的
synchronized(anObject)
{
value = map.get(key);
} 也会遇到这个问题
jsyx
2008-02-27
cammette 写道
jsyx 写道
cammette 写道
第一种这样会好点
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
value = map.get(key);
}
个人认为,这种写法不是线程安全的
为什么呢?
我们操作map时关注的是key对应的value。
只要我们改变某key的value能同步不就可以了吗?
你总要考虑到写的情况吧。
楼主的测试使用的是HashMap。
在java中,hashmap内部是使用数组来实现的。
无论是put还是get,首先都要根据key的hash值以及数组的长度以及一些其他的常数,计算出一个位置,然后对应get/put,会在这个位置内搜寻或者放置value。当map中存入的对象的个数到了一个临界值时(threshold),hashmap会重新初始化一个新的更长的数组,并且会重新分配所有已存的对象。
public V get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry<K,V> e = table[i];
while (true) {
if (e == null)
return null;
if (e.hash == hash && eq(k, e.key))
return e.value;
e = e.next;
}
}
public V put(K key, V value) {
K k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
if (e.hash == hash && eq(k, e.key)) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, k, value, i);
return null;
}
举例来说:
如果你只同步key,那么当执行到这一行,以后
int i = indexFor(hash, table.length);
另外一个线程执行了一个新的put操作,导致数组被resize,对象被重新放置。
这样的结果就是你的get操作取不出正确的value或者直接返回null
/**
* Rehashes the contents of this map into a new array with a
* larger capacity. This method is called automatically when the
* number of keys in this map reaches its threshold.
*
* If current capacity is MAXIMUM_CAPACITY, this method does not
* resize the map, but sets threshold to Integer.MAX_VALUE.
* This has the effect of preventing future calls.
*
* @param newCapacity the new capacity, MUST be a power of two;
* must be greater than current capacity unless current
* capacity is MAXIMUM_CAPACITY (in which case value
* is irrelevant).
*/
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
cammette
2008-02-27
jsyx 写道
cammette 写道
第一种这样会好点
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
value = map.get(key);
}
个人认为,这种写法不是线程安全的
为什么呢?
我们操作map时关注的是key对应的value。
只要我们改变某key的value能同步不就可以了吗?
galaxystar
2008-02-26
dynamic hash也是ConcurrentHashMap一大性能亮点,虽然它是同步的
jsyx
2008-02-26
cammette 写道
第一种这样会好点
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
value = map.get(key);
}
个人认为,这种写法不是线程安全的
cammette
2008-02-26
第一种这样会好点
synchronized(key)
{
value = map.get(key);
}
synchronized(key)
{
value = map.get(key);
}
likeblood
2008-02-26
SynchronizedThread 类的同步中 楼主有没有测试不要同步SynchronizedThread.class的情况 你可以同步一个Object,来测试一下时间
dennis_zane
2008-02-25
内部锁在jdk6上已经有比较大的改进,ConcurrentHashMap采用16个分离锁,当然比独占锁快多了。
mllee
2008-02-24
测试代码。只图方便了,不大 OO,见笑。
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class MapTest
{
public static final int THREAD_COUNT = 1;
public static final int MAP_SIZE = 1000;
public static final int EXECUTION_MILLES = 1000;
public static final int[] KEYS = new int[100];
public static void main(String[] args) throws Exception
{
//初始化
Random rand = new Random();
for (int i = 0; i < KEYS.length; ++i)
{
KEYS[i] = rand.nextInt();
}
//创建线程
long start = System.currentTimeMillis();
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i)
{
//threads[i] = new UnsafeThread();
//threads[i] = new SynchronizedThread();
//threads[i] = new LockThread();
//threads[i] = new ReadLockThread();
threads[i] = new ConcurrentThread();
threads[i].start();
}
//等待其它线程执行若干时间
Thread.sleep(EXECUTION_MILLES);
//统计 get 操作的次数
long sum = 0;
for (int i = 0; i < THREAD_COUNT; ++i)
{
sum += threads[i].getClass().getDeclaredField("count").getLong(threads[i]);
}
long millisCost = System.currentTimeMillis() - start;
System.out.println(sum + "(" + (millisCost) + "ms)");
System.exit(0);
}
public static void fillMap(Map<Integer, Integer> map)
{
Random rand = new Random();
for (int i = 0; i < MAP_SIZE; ++i)
{
map.put(rand.nextInt(), rand.nextInt());
}
}
}
class UnsafeThread extends Thread
{
private static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
public long count = 0;
static
{
MapTest.fillMap(map);
}
public void run()
{
for (;;)
{
int index = (int)(count % MapTest.KEYS.length);
map.get(MapTest.KEYS[index]);
++count;
}
}
}
class SynchronizedThread extends Thread
{
private static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
public long count = 0;
static
{
MapTest.fillMap(map);
}
public void run()
{
for (;;)
{
int index = (int)(count % MapTest.KEYS.length);
synchronized(SynchronizedThread.class)
{
map.get(MapTest.KEYS[index]);
}
++count;
}
}
}
class LockThread extends Thread
{
private static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
private static Lock lock = new ReentrantLock();
public long count = 0;
static
{
MapTest.fillMap(map);
}
public void run()
{
for (;;)
{
int index = (int)(count % MapTest.KEYS.length);
lock.lock();
map.get(MapTest.KEYS[index]);
lock.unlock();
++count;
}
}
}
class ReadLockThread extends Thread
{
private static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
private static Lock lock = new ReentrantReadWriteLock().readLock();
public long count = 0;
static
{
MapTest.fillMap(map);
}
public void run()
{
for (;;)
{
int index = (int)(count % MapTest.KEYS.length);
lock.lock();
map.get(MapTest.KEYS[index]);
lock.unlock();
++count;
}
}
}
class ConcurrentThread extends Thread
{
private static Map<Integer, Integer> map = new ConcurrentHashMap<Integer, Integer>();
public long count = 0;
static
{
MapTest.fillMap(map);
}
public void run()
{
for (;;)
{
int index = (int)(count % MapTest.KEYS.length);
map.get(MapTest.KEYS[index]);
++count;
}
}
}发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 602 次
- 性别:

- 来自: 深圳

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
Map 四种同步方式的性能比 ...
看楼主的图很吓人,synchronized效率这么差啊,jdk1.4的也只能用这 ...
-- by qiuyuanshan -
Map 四种同步方式的性能比 ...
jomper 写道上面的评论相当的精彩我请教一下为什么不是 synchroniz ...
-- by dagzhao -
Map 四种同步方式的性能比 ...
上面的评论相当的精彩我请教一下为什么不是 synchronized(map){ ...
-- by jomper -
Map 四种同步方式的性能比 ...
cammette 写道jsyx 写道cammette 写道jsyx 写道camm ...
-- by jsyx -
Map 四种同步方式的性能比 ...
jsyx 写道cammette 写道jsyx 写道cammette 写道第一种这 ...
-- by cammette






评论排行榜