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 acquire out possible. Out of many useful methods, 1 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() business office tries to compute a mapping for the specified substitution together with its electrical current mapped value (or cypher if in that place is no electrical current mapping). The entire business office is performed atomically.
Some attempted update operations on this map past times other threads may live on blocked spell the computation is inward progress, so the computation should live on curt together with simple, together with must non drive to update whatever other mappings of this Map. In uncomplicated words, y'all tin purpose this method to atomically update a value for a given substitution inward the ConcurrentHashMap.
You tin purpose compute() method to update an existing value within ConcurrenHashMap. For example, to either practice or append a String msg to a value mapping:
map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
If the business office returns null, the mapping is removed (or remains absent if initially absent).
If the business office itself throws an (unchecked) exception, the exception is rethrown, together with the electrical current mapping is left unchanged
There are besides variants of compute() method e.g. computeIfPresent() together with computeIfAbsent(), which computes the novel value solely if an existing value is introduce or absent.
For example, y'all tin update a map of LongAdder using computeIfAbsent equally shown below:
map.computeIfAbsent(key, k -> novel LongAdder()).increment();
Here the constructor of LongAdder shape volition solely live on called when a novel counter is truly needed. If a value exists together with so it is returned from ConcurrentHashMap, similar to the putIfAbsent() method. You tin farther see ConcurrentHashMap.
Now, let's evidence to sympathise what's happening here.
In the start line, nosotros accept exactly created a Concurrent HashMap alongside ii keys apple tree together with mango, together with their values are their count e.g. how many apples nosotros accept together with how many mangoes nosotros have.
Now, nosotros got 1 to a greater extent than apple tree together with nosotros bespeak to update the count on our bucket, for that, nosotros are calling the compute() method equally shown below:
This is exactly incrementing the value for this key, therefore 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 together with our chore is to add together keys together with their counts inward existent time. This is suited for scenarios similar y'all are doing a sale together with y'all bespeak to acquire out along rail of how many copies of a item mass or course of report is sold.
Another useful scenario is reading through a text file together with printing the count of each discussion appear inward the file.
Anyway, the substitution signal hither is that the map is initially empty which is shown inward the 3rd impress statement. After that, nosotros accept added 2 apples together with 1 mango inward this map using computeIfAbsent() method together with it has created a LongAdder object for each substitution together with stored that equally value.
The skilful affair virtually this method is that LongAdder object is solely created when a substitution is start fourth dimension added i.e. it was absent initially, subsequently that, the count is incremented inward LongAdder object.
This is a much amend agency to growth a counter inward a concurrent Java application, but LongAdder is solely available from Java 8.
That's why when nosotros printed map2, nosotros run into that in that place are ii apples together with 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 virtually LongAdder and several other useful novel classes added in JDK 8 API.
Here is the screenshot of this plan alongside output:
Here are a couplet 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() together with computeIfPresent() which computes values accordingly.
3) You tin besides purpose merge() inward house of the compute() for updating an existing value.
That's all virtually how to purpose the compute() method inward Java 8. You tin purpose this method to update the values of a item substitution inward ConcurrentHashMap. You tin besides purpose to insert count for novel keys. It's peculiarly useful for populating a concurrent hash map alongside keys together with their counts e.g. reading a text file together with impress counts of all words.
Further Reading
5 Books to Learn Java 8 from Scratch5 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 purpose the filter method inward Java 8 10 Java 8 Stream Interview Questions alongside Answers How to purpose the forEach method inward Java 8
Some attempted update operations on this map past times other threads may live on blocked spell the computation is inward progress, so the computation should live on curt together with simple, together with must non drive to update whatever other mappings of this Map. In uncomplicated words, y'all tin purpose this method to atomically update a value for a given substitution inward the ConcurrentHashMap.
You tin purpose compute() method to update an existing value within ConcurrenHashMap. For example, to either practice or append a String msg to a value mapping:
map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
If the business office returns null, the mapping is removed (or remains absent if initially absent).
If the business office itself throws an (unchecked) exception, the exception is rethrown, together with the electrical current mapping is left unchanged
There are besides variants of compute() method e.g. computeIfPresent() together with computeIfAbsent(), which computes the novel value solely if an existing value is introduce or absent.
For example, y'all tin update a map of LongAdder using computeIfAbsent equally shown below:
map.computeIfAbsent(key, k -> novel LongAdder()).increment();
Here the constructor of LongAdder shape volition solely live on called when a novel counter is truly needed. If a value exists together with 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 purpose 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 together with 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 besides purpose compute() together with lambda appear to // atomically update a value or mapping inward ConcurrentHashMap map.compute("apple", (key, value) -> value == null ? 1 : value + 1); System.out.println("map subsequently calling compute on apple: " + map); // y'all tin besides purpose computeIfAbsent() or computeIfPresent() method // Constructor of LongAdder volition live on solely called when a value for // given substitution is non exists ConcurrentMap<String, LongAdder> map2 = new ConcurrentHashMap<>(); System.out.println("map alongside LongAdder earlier calling compute: " + map2); map2.computeIfAbsent("apple", substitution -> new LongAdder()).increment(); map2.computeIfAbsent("mango", substitution -> new LongAdder()).increment(); map2.computeIfAbsent("apple", substitution -> new LongAdder()).increment(); System.out.println("map alongside LongAdder subsequently calling compute on apple, mango, apple: " + map2); } } Output: map earlier calling compute: {apple=3, mango=4} map subsequently calling compute on apple: {apple=4, mango=4} map alongside LongAdder earlier calling compute: {} map alongside LongAdder subsequently calling compute on apple, mango, apple: {apple=2, mango=1}
Now, let's evidence to sympathise what's happening here.
In the start line, nosotros accept exactly created a Concurrent HashMap alongside ii keys apple tree together with mango, together with their values are their count e.g. how many apples nosotros accept together with how many mangoes nosotros have.
Now, nosotros got 1 to a greater extent than apple tree together with nosotros bespeak to update the count on our bucket, for that, nosotros are calling the compute() method equally shown below:
map.compute("apple", (key, value) -> value == null ? 1 : value + 1);
This is exactly incrementing the value for this key, therefore 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 together with our chore is to add together keys together with their counts inward existent time. This is suited for scenarios similar y'all are doing a sale together with y'all bespeak to acquire out along rail of how many copies of a item mass or course of report is sold.
Another useful scenario is reading through a text file together with printing the count of each discussion appear inward the file.
Anyway, the substitution signal hither is that the map is initially empty which is shown inward the 3rd impress statement. After that, nosotros accept added 2 apples together with 1 mango inward this map using computeIfAbsent() method together with it has created a LongAdder object for each substitution together with stored that equally value.
The skilful affair virtually this method is that LongAdder object is solely created when a substitution is start fourth dimension added i.e. it was absent initially, subsequently that, the count is incremented inward LongAdder object.
This is a much amend agency to growth a counter inward a concurrent Java application, but LongAdder is solely available from Java 8.
That's why when nosotros printed map2, nosotros run into that in that place are ii apples together with 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 virtually LongAdder and several other useful novel classes added in JDK 8 API.
Here is the screenshot of this plan alongside output:
Important points virtually compute() method of Java 8
Now that y'all know what is compute() method together with what does it practice together with how to purpose it inward a Java program, its fourth dimension to revise around of the of import things virtually this method.Here are a couplet 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() together with computeIfPresent() which computes values accordingly.
3) You tin besides purpose merge() inward house of the compute() for updating an existing value.
That's all virtually how to purpose the compute() method inward Java 8. You tin purpose this method to update the values of a item substitution inward ConcurrentHashMap. You tin besides purpose to insert count for novel keys. It's peculiarly useful for populating a concurrent hash map alongside keys together with their counts e.g. reading a text file together with impress counts of all words.
Further Reading
5 Books to Learn Java 8 from Scratch
Thanks for reading this article so far. If y'all similar this tutorial together with so delight part alongside your friends together with colleagues, if y'all accept whatever query or dubiety together with so delight drib a comment.
P. S. - If y'all are looking for around costless courses to acquire recent changes on Java 8 together with Java nine together with so y'all tin besides run into this listing of Free Java 8 together with nine Courses for Programmers.
P. S. - If y'all are looking for around costless courses to acquire recent changes on Java 8 together with Java nine together with so y'all tin besides run into this listing of Free Java 8 together with nine Courses for Programmers.
No comments:
Post a Comment