Java Viii Concurrenthashmap Compute() In Addition To Computeifpresent() Example

The JDK 8 has added several useful methods inward existing interfaces e.g. java.util.Map, java.util.Collection, and java.util.concurrent.ConcurrentMap. Thanks to default methods, the much-needed development of existing interfaces popular off possible. Out of many useful methods, i method which stands out to me is the compute() method, which allows y'all to update a value inward ConcurrentHashMap atomically. As per Java documentation, The compute() run tries to compute a mapping for the specified fundamental in addition to its electrical flow mapped value (or nix if at that spot is no electrical flow mapping). The entire run is performed atomically.

Some attempted update operations on this map past times other threads may endure blocked piece the computation is inward progress, so the computation should endure curt in addition to simple, in addition to must non endeavor to update whatever other mappings of this Map. In uncomplicated words, y'all tin exercise this method to atomically update a value for a given fundamental inward the ConcurrentHashMap.

You tin exercise compute() method to update an existing value within ConcurrenHashMap. For example, to either exercise or append a String msg to a value mapping:

map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))

If the run returns null, the mapping is removed (or remains absent if initially absent).

If the run itself throws an (unchecked) exception, the exception is rethrown, in addition to the electrical flow mapping is left unchanged

There are likewise variants of compute() method e.g. computeIfPresent() in addition to computeIfAbsent(), which computes the novel value alone if an existing value is introduce or absent.

For example, y'all tin update a map of LongAdder using computeIfAbsent every bit shown below:

map.computeIfAbsent(key, k -> novel LongAdder()).increment();

Here the constructor of LongAdder cast volition alone endure called when a novel counter is truly needed. If a value exists in addition to so it is returned from ConcurrentHashMap, similar to the putIfAbsent() method.  You tin farther see ConcurrentHashMap.

import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.LongAdder;  /*  * Java Program to exercise compute() method of Java 8  * to atomically update values inward ConcurrentHashMap  */ public class Hello {    public static void main(String[] args) throws Exception {      // a ConcurrentHashMAp of string keys in addition to Long values     ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();     map.put("apple", 3);     map.put("mango", 4);          System.out.println("map earlier calling compute: " + map);      // inward JDK 8 - y'all tin likewise exercise compute() in addition to lambda facial expression to     // atomically update a value or mapping inward ConcurrentHashMap     map.compute("apple", (key, value) -> value == null ? 1 : value + 1);          System.out.println("map afterwards calling compute on apple: " + map);      // y'all tin likewise exercise computeIfAbsent() or computeIfPresent() method     // Constructor of LongAdder volition endure alone called when a value for     // given fundamental is non exists     ConcurrentMap<String, LongAdder> map2 = new ConcurrentHashMap<>();             System.out.println("map amongst LongAdder earlier calling compute: " + map2);          map2.computeIfAbsent("apple", fundamental -> new LongAdder()).increment();     map2.computeIfAbsent("mango", fundamental -> new LongAdder()).increment();     map2.computeIfAbsent("apple", fundamental -> new LongAdder()).increment();          System.out.println("map amongst LongAdder afterwards calling compute on                              apple, mango, apple: " + map2);    } }  Output: map earlier calling compute: {apple=3, mango=4} map afterwards calling compute on apple: {apple=4, mango=4} map amongst LongAdder earlier calling compute: {} map amongst LongAdder afterwards calling compute on apple, mango, apple: {apple=2, mango=1}


Now, let's seek to sympathize what's happening here.

In the start line, nosotros accept only created a Concurrent HashMap amongst 2 keys apple tree in addition to mango, in addition to their values are their count e.g. how many apples nosotros accept in addition to how many mangoes nosotros have.

Now, nosotros got i to a greater extent than apple tree in addition to nosotros demand to update the count on our bucket, for that, nosotros are calling the compute() method every bit shown below:

map.compute("apple", (key, value) -> value == null ? 1 : value + 1);

This is precisely incrementing the value for this key, thence the count of "apple" moved from iii to 4, which is shown inward our minute impress statement.

In the minute example, nosotros accept an empty ConcurrentHashMap in addition to our labor is to add together keys in addition to their counts inward existent time. This is suited for scenarios similar y'all are doing a sale in addition to y'all demand to continue rails of how many copies of a detail mass or class is sold.

Another useful scenario is reading through a text file in addition to printing the count of each give-and-take appear inward the file.

Anyway, the fundamental quest hither is that the map is initially empty which is shown inward the 3rd impress statement. After that, nosotros accept added 2 apples in addition to 1 mango inward this map using computeIfAbsent() method in addition to it has created a LongAdder object for each fundamental in addition to stored that every bit value.

The skillful affair most this method is that LongAdder object is alone created when a fundamental is start fourth dimension added i.e. it was absent initially, afterwards that, the count is incremented inward LongAdder object.

This is a much improve agency to growth a counter inward a concurrent Java application, but LongAdder is alone available from Java 8.

That's why when nosotros printed map2, nosotros come across that at that spot are 2 apples in addition to 1 mango is introduce inward our concurrent map. You tin farther see The Ultimate Java 8 Tutorial - From beginner to professional to acquire to a greater extent than most LongAdder and several other useful novel classes added in JDK 8 API.

Here is the screenshot of this plan amongst output:

 has added several useful methods inward existing interfaces e Java 8 ConcurrentHashMap compute() in addition to computeIfPresent() Example


Important points most compute() method of Java 8

Now that y'all know what is compute() method in addition to what does it exercise in addition to how to exercise it inward a Java program, its fourth dimension to revise unopen to of the of import things most this method.

Here are a brace of points which is worth remembering:

1) It allows y'all to atomically update a value inward ConcurrentHashMap.

2) It has variants e.g. computeIfAbsent() in addition to computeIfPresent() which computes values accordingly.

3) You tin likewise exercise merge() inward house of the compute() for updating an existing value.


That's all most how to exercise the compute() method inward Java 8. You tin exercise this method to update the values of a detail fundamental inward ConcurrentHashMap. You tin likewise exercise to insert count for novel keys. It's especially useful for populating a concurrent hash map amongst keys in addition to their counts e.g. reading a text file in addition to impress counts of all words.

Further Reading
5 Books to Learn Java 8 from Scratch
  • 5 Courses to acquire Java 8 in-depth
  • How to bring together String inward Java 8
  • How to variety HasMap past times values inward Java 8?
  • 10 examples of Optional inward Java 8?
  • How to variety the map past times keys inward Java 8?
  • How to exercise the filter method inward Java 8
  • 10 Java 8 Stream Interview Questions amongst Answers
  • How to exercise the forEach method inward Java 8

  • Thanks for reading this article so far. If y'all similar this tutorial in addition to so delight portion amongst your friends in addition to colleagues, if y'all accept whatever interrogation or uncertainty in addition to so delight drib a comment.

    P. S. - If y'all are looking for unopen to costless courses to acquire recent changes on Java 8 in addition to Java nine in addition to so y'all tin likewise come across this listing of Free Java 8 in addition to nine Courses for Programmers.

    0 Response to "Java Viii Concurrenthashmap Compute() In Addition To Computeifpresent() Example"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel