标签 - 代码

代码    2016-03-17 18:31:50    481    0    0

代码如下:

private static final Map<String, AtomicInteger> map = new HashMap<String, AtomicInteger>();
    private static final Object locker = new Object();

    public void increase(String key) {
        AtomicInteger count = map.get(key);
        if (count == null) {
            synchronized (locker) {
                if (map.get(key) == null) {
                    count = new AtomicInteger();
                    map.put(key, count);
                }
            }
        }
        count.incrementAndGet();
    }

上面的代码会报空指针异常
正确代码应该如下:

private static final Map<String, AtomicInteger> map = new HashMap<String, AtomicInteger>();
    private static final Object locker = new Object();

    public void increase(String key) {
        if (map.get(key) == null) {
            synchronized (locker) {
                if (map.get(key) == null) {
                    count = new AtomicInteger();
                    map.put(key, count);