3 ms·
To me, the single most useful/important addition to Java 8 ConcurrentHashMap is the addition and implementation of "computeIfAbsent". With CHM and computeIfAbs
by astral303 10y ago
To me, the single most useful/important addition to Java 8 ConcurrentHashMap is the addition and implementation of "computeIfAbsent".
With CHM and computeIfAbsent, it's easy to write lazy loading "by key" (i.e. simple caches). Prior to Java 8, I had to resort to Guava's LoadingCache.
- pdpi 10y agocompute and computeIfPresent are also pretty damn useful (especially in the "atomically modify a value, then delete it if it meets a condition" kind of scenarios)
- alkonaut 10y agoWait, it had a concurrenthashmap but no way to "get or add"? Is a concurrent hash map even useful without that? (I suppose you could always write your own with some read/write locking but...wow)
- LgWoodenBadger 10y agoConcurrentMap has always had putIfAbsent(). That requires the thing that you're putting to have been constructed prior to the call. computeIfAbsent() allows you to pass in a lambda (a Function really) which will only be called if necessary, thus avoiding a potentially unnecessary Object creation/etc.