私はここに答えを投稿しました。ここで、読み取りputIfAbsent
方法の使用を示すコードは次のとおりです。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 n'をダウンロードしていません。または、公式(会社のポリシー)になるまでダウンロードできますので、これをテストすることはできませんが、このようなものは有効で効果的ですか?
public long addTo(String key, long value) {
return map.putIfAbsent( key, () -> new AtomicLong(0) ).addAndGet(value);
}
ラムダを使用しnew AtomicLong(0)
て、マップに存在しないために作成する必要があると実際に判断されるまで、の評価を遅らせることを望んでいます。
ご覧のとおり、これははるかに簡潔で機能的です。
基本的に、私の質問は次のとおりだと思います。
- これは機能しますか?
- または、ラムダを完全に誤解しましたか?
- いつかこのようなことがうまくいくでしょうか?