化妆品网站开发流程和进度安排,做家具网站要多少钱,wordpress怎么可视化构建页面,建设工程项目管理中心总览 Java 8库在地图上有一个新方法#xff0c;computeIfAbsent。 这是一种非常有用的将地图变成与键关联的对象的缓存的方法。 但是#xff0c;您可能没有考虑过一种组合。 如果您在内部调用computeIfAbsent会发生什么。 map.computeIfAbsent(Key.Hello, s - {map.com… 总览 Java 8库在地图上有一个新方法computeIfAbsent。 这是一种非常有用的将地图变成与键关联的对象的缓存的方法。 但是您可能没有考虑过一种组合。 如果您在内部调用computeIfAbsent会发生什么。 map.computeIfAbsent(Key.Hello, s - {map.computeIfAbsent(Key.Hello, t - 1);return 2;
});enum Key {Hello} 尽管这在简单的情况下看起来很奇怪但是在更复杂的代码中您可能会偶然地这样做就像我今天下午所做的那样那么会发生什么呢 好吧这取决于您使用的集合。 HashMap: {Hello2}
WeakHashMap: {Hello2}
TreeMap: {Hello2}
IdentityHashMap: {Hello2}
EnumMap: {Hello2}
Hashtable: {Hello2, Hello1}
LinkedHashMap: {Hello1, Hello2}
ConcurrentSkipListMap: {Hello1}
ConcurrentHashMap: 注意 ConcurrentHashMap永不返回。 它的锁定似乎没有重入。 ConcurrentSkipListMap具有最合理的结果保留第一个添加的值。 如果令人困惑Hello 2对于这种不确定的情况是合理的因为它是第二个值而不是第一个值。 没有什么意义的是让唯一的不可变键出现两次。 不幸的是ConcurrentHashMap死锁本身是不幸的但至少不是那么微妙。 完整的代码。 public class A {public static void main(String[] args) {for (Map map : new Map[]{new HashMap(),new WeakHashMap(),new TreeMap(),new IdentityHashMap(),new EnumMap(Key.class),new Hashtable(),new LinkedHashMap(),new ConcurrentSkipListMap(),new ConcurrentHashMap()}) {System.out.print(map.getClass().getSimpleName() : );map.computeIfAbsent(Key.Hello, s - {map.computeIfAbsent(Key.Hello, t - 1);return 2;});System.out.println(map);}}enum Key {Hello}
} 方法compute具有相似的结果 HashMap: {Hellonull2}
WeakHashMap: {Hellonull2}
TreeMap: {Hellonull2}
IdentityHashMap: {Hellonull2}
EnumMap: {Hellonull2}
Hashtable: {Hellonull2, Hello1}
LinkedHashMap: {Hello1, Hellonull2}
ConcurrentSkipListMap: {Hello12} ConcurrentHashMap public class A {public static void main(String[] args) {for (Map map : new Map[]{new HashMap(),new WeakHashMap(),new TreeMap(),new IdentityHashMap(),new EnumMap(Key.class),new Hashtable(),new LinkedHashMap(),new ConcurrentSkipListMap(),new ConcurrentHashMap()}) {System.out.print(map.getClass().getSimpleName() : );map.compute(Key.Hello, (s, v) - {map.compute(Key.Hello, (s2, v2) - 1);return v 2;});System.out.println(map);}}enum Key {Hello}
}结论 如果您要在lambda内部嵌套对地图的调用则需要特别小心或者完全避免这样做。 如果必须这样做ConcurrentSkipListMap似乎表现最佳。 翻译自: https://www.javacodegeeks.com/2015/05/puzzler-nested-computeifabsent.html