我张贴解答here,其中展示了使用ConcurrentMap
的putIfAbsent
方法的代码如下:lambda表达式和的putIfAbsent
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;
}
这种方法的主要缺点是,你必须创建一个新的对象装进映射它是否会被使用。如果物体很重,这可能会产生重大影响。
我突然想到,这将是使用Lambda表达式的机会。我没有下载Java 8 n'or我将能够,直到它是正式的(公司政策),所以我不能测试这个,但这样的事情是有效的和有效的?
public long addTo(String key, long value) {
return map.putIfAbsent(key,() -> new AtomicLong(0)).addAndGet(value);
}
我希望能使用拉姆达延迟new AtomicLong(0)
的评价,直到它实际上是决定了它应建立,因为它没有在地图上存在。
正如你可以看到这是更简洁和实用。
从本质上讲,我想我的问题是:
- 将这项工作?
- 还是我完全曲解lambda表达式?
- 这样的工作有一天可能会奏效吗?
你怎么无法下载Java 8并自行测试?您的公司是否阻止您在工作计算机上安装任何东西(甚至用于评估目的)?那么在你的个人身上尝试一下呢? – 2013-02-14 14:31:13
@SimonLehmann - 顺便说一句 - 在您发表评论后,我安装了Java 8,它不仅没有Lambdas(还有一些额外的东西我应该安装,但没有解决),但DBVisualiser停止工作 - 所以我删除了它。抱歉。也许明年。 – OldCurmudgeon 2013-03-02 00:25:29