首页  

Map computeIfAbsent 实例     所属分类 java8 浏览量 1072
JAVA8 Map接口  新增方法 computeIfAbsent
public V computeIfAbsent(K key, Function< ? super K,? extends V> mappingFunction)


ConcurrentHashMap computeIfAbsent 线程安全
computeIfAbsent 不要修改集合 (put 等操作) ,可能导致死循环


import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; public class ComputeIfAbsentTest { static Map<String,AtomicLong> map = new HashMap<>(); public static void main(String[] args) throws Exception { String key = "a"; System.out.println(increment(key)); System.out.println(increment(key)); System.out.println(increment(key)); Function<String,AtomicLong> nullResult = (k) -> {return null;}; Function<String,AtomicLong> errorFunction = (k) -> {throw new RuntimeException("error");}; key = "b"; // null 值 不会 put 进去 map.computeIfAbsent(key, nullResult); try { key = "c"; map.computeIfAbsent(key, errorFunction); }catch(Throwable e) { System.out.println(e); } System.out.println(map); } private static long increment(String key) { if(key==null) { return 0; } AtomicLong count = map.computeIfAbsent(key, (k)-> new AtomicLong(0)); return count.incrementAndGet(); } }

上一篇     下一篇
tomcat nio 读写关键代码

springboot2动态设置日志级别

postman上传文件

励志歌曲系列

jdk16 ZGC 改进

字符串编辑距离 Levenstein edit distance