2007年12月5日星期三

线程安全的读优化Map实现

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 本技术适用于共享数据很少更改且由多线程同时访问的场合。不过该技术仅适用于应用程序不要求使用绝对最新数据的场合。
 * 最终结果是并发访问随时间变化的共享数据。在要求高并发性的环境中。该技术可以避免在应用程序内部包含不必要的排队点。
 * 仅用于 Java 5.0 及更高版本。
 * @author xued
 */
public class ReadNoLockingMap {

    // 必须设为volatile类型以确保消费线程可以得到更新后的值
    private volatile Map currentMap;
    private Object lockbox;

    public ReadNoLockingMap() {
        this.currentMap = new HashMap();
        this.lockbox = new Object();
    }

    public void putNewMap(Object key, Object value) {
        synchronized (lockbox) {
            Map newMap = new HashMap(currentMap);
            newMap.put(key, value);
            currentMap = newMap;
        }
    }

    public void putNewMap(Map t) {
        synchronized (lockbox) {
            Map newMap = new HashMap(currentMap);
            newMap.putAll (t);
            currentMap = newMap;
        }
    }

    public Object getFromCurrentMap(Object key) {  // Called by consumer threads.
        Map m = currentMap; // No locking around this is required.
        Object result = m.get(key);     // get on a HashMap is not synchronized.
        return (result); // Do any additional processing needed using the result.
    }

    public static void main(String[] args) {
        final ReadNoLockingMap nlMap = new ReadNoLockingMap();
        nlMap.putNewMap("key", "Starting...");
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                        public void run() {
                            int value = new Random().nextInt();
                            nlMap.putNewMap("key", value);
                            System.out.println(Thread.currentThread().getName() + ": write map " + value);
                        }
                    }).start();
        }

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                    public void run() {
                            System.out.println(Thread.currentThread().getName() + ": " + nlMap.getFromCurrentMap("key"));
                    }
                }).start();
        }
    }
}

没有评论: