【Java并发编程】ConcurrentHashMap注意问题

ConcurrentHashMap通常只被看做并发效率更高的Map,用来替换其他线程安全的Map容器,比如Hashtable和Collections.synchronizedMap。实际上,线程安全的容器,特别是Map,应用场景没有想象中的多,很多情况下一个业务会涉及容器的多个操作,即复合操作,并发执行时,线程安全的容器只能保证自身的数据不被破坏,但无法保证业务的行为是否正确。

举个例子:统计文本中单词出现的次数,把单词出现的次数记录到一个Map中,代码如下:

private final Map<String, Long> wordCounts = new ConcurrentHashMap<>();
 
public long increase(String word) {
    Long oldValue = wordCounts.get(word);
    Long newValue = (oldValue == null) ? 1L : oldValue + 1;
    wordCounts.put(word, newValue);
    return newValue;
}

如果多个线程并发调用这个increase()方法,increase()的实现就是错误的,因为多个线程用相同的word调用时,很可能会覆盖相互的结果,造成记录的次数比实际出现的次数少。

除了用锁解决这个问题,另外一个选择是使用ConcurrentMap接口定义的方法:

public interface ConcurrentMap<K, V> extendsMap<K, V> {
    V putIfAbsent(K key, V value);
    boolean remove(Object key, Object value);
    boolean replace(K key, V oldValue, V newValue);
    V replace(K key, V value);
}

这是个被很多人忽略的接口,也经常见有人错误地使用这个接口。ConcurrentMap接口定义了几个基于 CAS(Compare and Set)操作,很简单,但非常有用,下面的代码用ConcurrentMap解决上面问题:

private final ConcurrentMap<String, Long> wordCounts = newConcurrentHashMap<>();
 
public long increase(String word) {
    Long oldValue, newValue;
    while(true) {
        oldValue = wordCounts.get(word);
        if(oldValue == null) {
            // Add the word firstly, initial the value as 1
            newValue = 1L;
            if(wordCounts.putIfAbsent(word, newValue) == null) {
                break;
            }
        }else{
            newValue = oldValue + 1;
            if(wordCounts.replace(word, oldValue, newValue)) {
                break;
            }
        }
    }
    return newValue;
}

代码有点复杂,主要因为ConcurrentMap中不能保存value为null的值,所以得同时处理word不存在和已存在两种情况。

上面的实现每次调用都会涉及Long对象的拆箱和装箱操作,很明显,更好的实现方式是采用AtomicLong,下面是采用AtomicLong后的代码:

private final ConcurrentMap<String, AtomicLong> wordCounts = newConcurrentHashMap<>();
 
public long increase(String word) {
    AtomicLong number = wordCounts.get(word);
    if(number == null) {
        AtomicLong newNumber = newAtomicLong(0);
        number = wordCounts.putIfAbsent(word, newNumber);
        if(number == null) {
            number = newNumber;
        }
    }
    return number.incrementAndGet();
}

这个实现仍然有一处需要说明的地方,如果多个线程同时增加一个目前还不存在的词,那么很可能会产生多个newNumber对象,但最终只有一个newNumber有用,其他的都会被扔掉。对于这个应用,这不算问题,创建AtomicLong的成本不高,而且只在添加不存在词是出现。但换个场景,比如缓存,那么这很可能就是问题了,因为缓存中的对象获取成本一般都比较高,而且通常缓存都会经常失效,那么避免重复创建对象就有价值了。下面的代码演示了怎么处理这种情况:


private final ConcurrentMap<String, Future<ExpensiveObj>> cache = newConcurrentHashMap<>();
 
publicExpensiveObj get(finalString key) {
    Future<ExpensiveObj> future = cache.get(key);
    if(future == null) {
        Callable<ExpensiveObj> callable = newCallable<ExpensiveObj>() {
            @Override
            publicExpensiveObj call() throwsException {
                return newExpensiveObj(key);
            }
        };
        FutureTask<ExpensiveObj> task = newFutureTask<>(callable);
 
        future = cache.putIfAbsent(key, task);
        if(future == null) {
            future = task;
            task.run();
        }
    }
 
    try{
        returnfuture.get();
    }catch(Exception e) {
        cache.remove(key);
        throw new RuntimeException(e);
    }
}

解决方法其实就是用一个Proxy对象来包装真正的对象,跟常见的lazy load原理类似;使用FutureTask主要是为了保证同步,避免一个Proxy创建多个对象。注意,上面代码里的异常处理是不准确的。

最后再补充一下:

有条件的线程安全性 
同步的集合包装器 synchronizedMap 和 synchronizedList,有时也被称作有条件地线程安全——所有 单个的操作都是线程安全的,但是多个操作组成的操作序列却可能导致数据争用,因为在操作序列中控制流取决于前面操作的结果。下面的代码展示了公用的put-if-absent语句块——如果一个条目不在Map中,那么添加这个条目。不幸的是, 在containsKey()方法返回到put() 方法被调用这段时间内,可能会有另一个线程也插入一个带有相同键的值。如果您想确保只有一次插入,您需要用一个对Map m进行同步的同步块将这一对语句包装起来。

Map m = Collections.synchronizedMap(new HashMap());
List l = Collections.synchronizedList(new ArrayList());
// put-if-absent idiom -- contains a race condition
// may require external synchronization
if (!map.containsKey(key))
map.put(key, value);

信任的错觉 
synchronizedList 和 synchronizedMap提供的有条件的线程安全性也带来了一个隐患——开发者会假设,因为这些集合都是同步的,所以它们都是线程安全的,这样一来他们对于正确地同步混合操作这件事就会疏忽。其结果是尽管表面上这些程序在负载较轻的时候能够正常工作,但是一旦负载较重,它们就会开始抛出NullPointerException 或ConcurrentModificationException

参考文章:

https://blog.csdn.net/gjt19910817/article/details/47353909

https://blog.csdn.net/brandohero/article/details/39590351

猜你喜欢

转载自blog.csdn.net/fxkcsdn/article/details/86307047