JAVA并发编程随笔【十】ConcurrentMap.putIfAbsent用法

看如下的例子,我们从map中取指定key的值,如果key对应的值不存在则存入一个默认值,否则返回对应的值;这样在同步(单线程)环境下是没问题的,但是在多线程环境下就会出现问题,当if(!map.containsKey(key))判断的时候可能其他线程已经放入了对应的值,这样就可能导致取值不一致,造成线程不安全:

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

public class Test1 {

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

    public static String getValue(String key) {
        String value = new Object();
        if(!map.containsKey(key)) {
            map.put(key, value);
            return value;
        } else {
            return map.get(key);
        }
    }
    public static void main(String[] args) {
        map.put("12", "23");
        System.out.println(getValue("sd"));
        System.out.println(getValue("12"));
    }
}

为了解决这样的问题javase5引入了并发类ConcurrentMap中的putIfAbsent方法,正如文档中所描述的:

   /**
     * If the specified key is not already associated
     * with a value, associate it with the given value.
     * This is equivalent to
     * <pre>
     *   if (!map.containsKey(key))
     *       return map.put(key, value);
     *   else
     *       return map.get(key);</pre>
     * except that the action is performed atomically.
private static final ConcurrentMap<String, String> sub = new ConcurrentHashMap<String, String>();
map.putIfAbsent("12", "12");

putIfAbsent方法是原子性的,可以保证对集合的操作同步,不会出现线程安全问题;如果集合中已经存在对应的key就返回对应的值,否则将key、value存入集合,返回null,所以要对返回的值做一个判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值