

LongAdder /* * Java Program to use compute() method of Java 8 * to atomically update values in ConcurrentHashMap */ public class Hello You can further see The Complete Java MasterClass course on Udemy by Tim Buchalaka and his team to learn more about new methods added to the existing API in Java 8. If a value exists then it is returned from ConcurrentHashMap, similar to the putIfAbsent() method. Here the constructor of LongAdder class will only be called when a new counter is actually needed. Map.computeIfAbsent( key, k -> new LongAdder()).increment() There are also variants of compute() method like computeIfPresent() and computeIfAbsent(), which computes the new value only if an existing value is present or absent.įor example, you can update a map of LongAdder using computeIfAbsent as shown below: If the function itself throws an ( unchecked) exception, the exception is rethrown, and the current mapping is left unchanged If the function returns null, the mapping is removed (or remains absent if initially absent). Map.compute (key, (k, v) -> (v = null) ? msg : v.concat(msg)) For example, to either create or append a String msg to a value mapping: You can use the compute() method to update an existing value inside ConcurrenHashMap. In simple words, you can use this method to atomically update a value for a given key in the ConcurrentHashMap. Some attempted update operations on this map by other threads may be blocked while the computation is in progress, so the computation should be short and simple, and must not attempt to update any other mappings of this Map. The entire function is performed atomically. As per Java documentation, The compute() function tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). Out of many useful methods, one method which stands out to me is the compute() method, which allows you to update a value in ConcurrentHashMap atomically. Thanks to default methods, the much-needed evolution of existing interfaces becomes possible. The JDK 8 has added several useful methods in existing interfaces e.g.
