如果需要使 Map 线程安全,大致有这么四种方法:
1、使用 synchronized 关键字,这也是最原始的方法。代码如下
- synchronized(anObject)
- {
- value = map.get(key);
- }
JDK1.2 提供了 Collections.synchronizedMap(originMap) 方法,同步方式其实和上面这段代码相同。
Map Collections.synchronizedMap(Map m)
这个方法返回一个同步的Map,这个Map封装了底层的HashMap的所有方法,使得底层的HashMap即使是在多线程的环境中也是安全的。
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 方法调用次数的总和。为了比较,增加了未使用任何同步机制的情况(非安全!)。理论上,不同步应该最快。
我的测试结果:
转载文章的结果:
测试结果和转载文章中差不多,但是synchronized 貌似没有转载中说的那么糟糕。从附图可以看出:
1、不同步确实最快,与预期一致。
2、四种同步方式中,ConcurrentHashMap 是最快的,接近不同步的情况。
3、synchronized 关键字非常慢
4、使用读写锁的读锁,比普通所稍慢。
结论:
1、如果 ConcurrentHashMap 够用,则使用 ConcurrentHashMap。
2、如果需自己实现同步,则使用 JDK1.5 提供的锁机制,避免使用 synchronized 关键字。
测试代码:
- import java.util.*;
- import java.util.concurrent.*;
- import java.util.concurrent.locks.*;
- public class MapTest
- {
- public static final int THREAD_COUNT = 5;
- 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
- {
- //所有同类线程共享一个map
- private static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- //每个线程使用自己的计数器
- public long count = 0;
- //o必须是static,否则synchronized(o)每个线程只对自己的o加锁,锁没有效果
- private static final Object o = new Object();
- static
- {
- MapTest.fillMap(map);
- }
- public void run()
- {
- for (;;)
- {
- int index = (int)(count % MapTest.KEYS.length);
- // 没有锁效果的加锁方式:
- // (1)private final Object o = new Object();
- // synchronized(o)
- // (2)synchronized(this)
- // 有锁效果的加锁方式:
- // (1)synchronized(map)
- // (2)private static final Object o = new Object();
- // synchronized(o)
- 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;
- }
- }
- }
补充:
(1)虽然ConcurrentHashMap是线程安全的,而且性能很高,但是
看看下面一段代码:
- ConcurrentHashMap<String,String> map;
- String getString(String name) {
- String x = map.get(name);
- if (x == null) {
- x = new String();
- map.put(name, x);
- }
- return x;
- }
如果你只调用get(),或只调用put()时,ConcurrentHashMap是线程安全的。
但是,在你调用完get后,调用put之前,
如果有另外一个线程调用了map.put(name, x),
你再去执行map.put(name,x),
就很可能把前面的操作结果覆盖掉了。
所以,即使在线程安全的情况下,
你还是有可能违反原子操作的规则。
避免方法:将get和put放到一个锁下面
- Map map = Collections.synchronizedMap(new HashMap());
- String getString(String name) {
- synchronized(map){//可保证该同步块内的所有代码对map是一个原子操作。
- String x = map.get(name);
- if (x == null) {
- x = new String();
- map.put(name, x);
- }
- return x;
- }
- }