我在这里发布了一个答案,其中代码演示了readputIfAbsent方法的使用:ConcurrentMap
ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong> ();
public long addTo(String key, long value) {
  // The final value it became.
  long result = value;
  // Make a new one to put in the map.
  AtomicLong newValue = new AtomicLong(value);
  // Insert my new one or get me the old one.
  AtomicLong oldValue = map.putIfAbsent(key, newValue);
  // Was it already there? Note the deliberate use of '!='.
  if ( oldValue != newValue ) {
    // Update it.
    result = oldValue.addAndGet(value);
  }
  return result;
}
这种方法的主要缺点是您必须创建一个新对象以放入地图中,无论它是否会被使用。如果物体很重,这可能会产生重大影响。
我突然想到这将是一个使用 Lambdas 的机会。我还没有下载 Java 8,或者直到它正式发布(公司政策)之前我才能下载,所以我无法对此进行测试,但这样的东西是否有效?
public long addTo(String key, long value) {
  return map.putIfAbsent( key, () -> new AtomicLong(0) ).addAndGet(value);
}
我希望使用 lambda 来延迟对 的评估,new AtomicLong(0)直到它实际确定应该创建它,因为它在地图中不存在。
如您所见,这更加简洁和实用。
基本上我想我的问题是:
- 这行得通吗?
- 还是我完全误解了 lambda?
- 有一天这样的事情可能会奏效吗?