Map线程安全几种实现方法

来源:互联网 发布:井冈山大学网络平台 编辑:程序博客网 时间:2024/04/30 18:37

如果需要使 Map 线程安全,大致有这么四种方法: 
1、使用 synchronized 关键字,代码如下
synchronized(anObject) { 
  value = map.get(key);
}


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、不同步确实最快,与预期一致。 
2、四种同步方式中,ConcurrentHashMap 是最快的,接近不同步的情况。
3、synchronized 关键字非常慢,比使用锁慢了两个数量级。如果需自己实现同步,则使用 JDK1.5 提供的锁机制,避免使用 synchronized 关键字。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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 SynchronizedThread();
                    // threads[i] = new LockThread();
                    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 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;
                }
            }
        }

  转载自:http://www.cnblogs.com/cloudwind/archive/2012/08/30/2664003.html

import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TestMap {
Map<String, Map<String, Double>> mapall = new ConcurrentHashMap<String, Map<String, Double>>();public static void main(String args[]) {ExecutorService pool = Executors.newFixedThreadPool(500);for (int i = 0; i < 1000; i++) {Map<String, Double> map = new HashMap<String, Double>();map.put(i + 1 + "", (double) (i + 1));MyThread thread = new MyThread(map, i + "_all");pool.execute(thread);}pool.shutdown();int i = 0;for (Entry<String, Map<String, Double>> entry : TestMap.mapall.entrySet()) {i++;System.out.println("数据量:" + i);System.out.println(entry.getKey());}}}class MyThread extends Thread {Map<String, Double> map;String name;MyThread(Map<String, Double> map, String name) {this.map = map;this.name = name;}@Overridepublic void run() {<pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 13.3333px; line-height: 24px;">TestMap<span style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13.3333px;">.mapall.put(name, map);</span>
}


这个通过测试打印出来1000次,如果存成HashMap打印就不到1000次

0 0