在使用原子操作进行计数时,我们经常会用到ConcurrentHashMap,虽然ConcurrentHashMap是线程安全的,但是如果你操作的是其本身,并如果使用不当,也会造成很多线程安全问题。
看下面的例子,你觉得会输出多少呢?
public class ConcurrentHashMapTest {
private static final ConcurrentMap<String, AtomicInteger> CACHE_MAP = new ConcurrentHashMap<>();
private static final String KEY = "test";
private static class TestThread implements Runnable{
@Override
public void run() {
if(CACHE_MAP.get(KEY)==null){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
CACHE_MAP.put(KEY, new AtomicInteger());
}
CACHE_MAP.get(KEY).incrementAndGet();
}
}
public static void main(String[] args) {
new Thread(new TestThread()).start();
new Thread(new TestThread()).start();
new Thread(new TestThread()).start();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("次数:"+CACHE_MAP.get(KEY).get());
}
}
运行结果:
次数:1
我们有3个线程取访问,照理来说应该是3才对,为什么是1呢?
其实ConcurrentHashMap的put方法跟普通的HashMap没什么区别,如果key相同,依然会覆盖。
要想达到不覆盖,我们可以使用putIfAbsent()方法。
将CACHE_MAP.put(KEY, new AtomicInteger());
改为CACHE_MAP.putIfAbsent(KEY, new AtomicInteger());
运行结果如下:
次数:3
一般情况下,建议写一个公共的方法来获取CACHE_MAP中的value。对上面的代码进行优化后如下:
public class ConcurrentHashMapTest {
private static final ConcurrentMap<String, AtomicInteger> CACHE_MAP = new ConcurrentHashMap<>();
private static final String KEY = "test";
private static class TestThread implements Runnable{
@Override
public void run() {
getCacheValue(KEY).incrementAndGet();
}
}
public static AtomicInteger getCacheValue(String key){
if(CACHE_MAP.get(key)==null){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
CACHE_MAP.putIfAbsent(key, new AtomicInteger());
}
return CACHE_MAP.get(key);
}
public static void main(String[] args) {
new Thread(new TestThread()).start();
new Thread(new TestThread()).start();
new Thread(new TestThread()).start();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("次数:"+CACHE_MAP.get(KEY).get());
}
}
我们的效果达到了,再回头看看putIfAbsent()方法的源码:
public V put(K key, V value) {
Segment<K,V> s;
if (value == null)
throw new NullPointerException();
int hash = hash(key);
int j = (hash >>> segmentShift) & segmentMask;
if ((s = (Segment<K,V>)UNSAFE.getObject
(segments, (j << SSHIFT) + SBASE)) == null)
s = ensureSegment(j);
return s.put(key, hash, value, false);
}
public V putIfAbsent(K key, V value) {
Segment<K,V> s;
if (value == null)
throw new NullPointerException();
int hash = hash(key);
int j = (hash >>> segmentShift) & segmentMask;
if ((s = (Segment<K,V>)UNSAFE.getObject
(segments, (j << SSHIFT) + SBASE)) == null)
s = ensureSegment(j);
return s.put(key, hash, value, true);
}
其实put方法与putIfAbsent方法唯一的区别就在于调用s.put(…)方法时,最后一个参数,一个是false,一个是true。