How to occupation ConcurrentHashSet from ConcurrentHashMap inwards Java viii - Example Tutorial

There is no ConcurrentHashSet inwards JDK 8 but y'all tin withal exercise 1 for yourself yesteryear using the ConcurrentHashMap flat of java.util.concurrent package. There is a novel method added into ConcurrentHashMap inwards JDK 8, newKeySet(), which allows y'all to exercise a concurrent hash fix backed yesteryear a concurrent hash map. If y'all shout out back whenever y'all acquire keys from the map they are returned inwards a Set e.g. for the onetime keySet() method because map entirely has unique keys. Since map doesn't let duplicate keys, it tin last used equally a set, equally long equally y'all entirely tending for keys or but 1 element. That's why Java designers are added newKeySet() method to convert a map to set. This is equally good a static method, which way y'all don't demand a ConcurrentHashMap object to exercise a concurrent hash set.

The Set returned yesteryear the keySet() method is backed yesteryear a ConcurrentHashMap alongside given keys in addition to values are e'er Boolean.TRUE. It is equally good overloaded to conduct keep initial capacity to avoid internal re-sizing. If y'all know, the HashSet flat equally good internally uses an HashMap where values are e'er same, an object, which is possible because Map allows duplicate values.

Unlike the List returned yesteryear Arrays.asList(), which doesn't let y'all to add together or take away elements, the Set returned yesteryear newKeySet() is similar whatsoever normal Set implementations in addition to allows y'all add, take away or perform whatsoever other Set operation. You tin fifty-fifty top this Set to a method which is accepting a Set interface equally a parameter. I'll demonstrate this inwards coming example.




Java Program to exercise ConcurrentHashSet

Here is our Java programme to demonstrate how y'all tin generate a ConcurrentHashSet inwards JDK 8 yesteryear using the newKeSet() method added into java.util.concurrent.ConcurrentHashMap class. Even though I conduct keep used an object of the concurrent hash map here, it's non required because different keySet(), the newKeySet() is a static method.

Let's the code to genuinely generate a concurrent hash fix inwards Java 8:

import java.util.Set; import java.util.concurrent.ConcurrentHashMap;  /*  * Java Program to exercise ConcurrentHashSet from ConcurrentHashMap  * This code requires JDK 8 because nosotros purpose newKeySet() method  * which is entirely available inwards ConcurrentHashMap flat from JDK 8.   */ public class Demo {    public static void main(String[] args) throws Exception {      // measurement 1 - exercise a concurrent hashmap (optional)     ConcurrentHashMap<String, Integer> wordLengh = new ConcurrentHashMap<>();      // measurement ii - exercise a fix from map yesteryear using newKeySet() method     // supply size to forestall resizing in addition to ameliorate performance     Set<String> words = ConcurrentHashMap.newKeySet(wordLengh.size());      // measurement iii - y'all tin add together elements into set     words.add("Java");     words.add("JavaScript");      // measurement four - y'all tin take away elements from set     words.remove("JavaScript");      // measurement v - y'all tin equally good top this fix to whatsoever method expecting set     System.out.println(words);    }  }  Output: [Java]

You tin encounter that y'all tin easily add together in addition to take away elements from the Set returned yesteryear newKeySet() method. As I said, the Set is backed yesteryear ConcurrentHashMap, which way multiple readers tin retrieve values at the same fourth dimension in addition to equally good multiple writers tin insert values into the fix without blocking, until the read in addition to write functioning is happening inwards the same segment. You tin equally good see Java Fundamentals: Collections to larn to a greater extent than most the internal implementation of diverse collection classes of Java API.


Btw, If y'all remember, concurrent hash map never locks the whole map, instead, it divides the map into several segments, yesteryear default 16, equally good knowns equally concurrency flat in addition to entirely locks the segment where alteration is happening. This way multiple writes is possible if they are happening at different segments.

Btw, the concurrent hash fix is non entirely thread-safe fix which is available inwards JDK, y'all conduct keep approximately to a greater extent than choices e.g. y'all tin purpose CopyOnWriteArraySet, which is similar to CopyOnWriteArrayList i.e. it copies the whole collection into novel 1 whenever a write happens but because of this demeanor they are entirely useful for a fix alongside pocket-sized pose out of elements alongside infrequent write. You tin farther read the Java: H5N1 Beginners Guide sixth Edition for to a greater extent than details on concurrent collection classes.

 but y'all tin withal exercise 1 for yourself yesteryear using the  How to exercise ConcurrentHashSet from ConcurrentHashMap inwards Java 8 - Example Tutorial


That's all most how to convert ConcurrentHashMap to ConcurrentHashSet inwards Java. This is a prissy picayune tip which allows y'all to purpose a map equally Set alongside all the concurrency benefits provided yesteryear concurrent hash map without whatsoever extra effort. They newKeySet() is similar whatsoever static manufactory method, which y'all tin invoke alongside the flat get upwardly without fifty-fifty needing a ConcurrentHashMap object.

Further Learning
Java Fundamentals: Collections
Java Fundamentals: The Core Platform
From Collections to Streams inwards Java 8 Using Lambda Expressions


Other Java Collection tutorials y'all may like
How HashMap internally plant inwards Java? (answer)
What is the departure betwixt HashSet, TreeSet, in addition to LinkedHashSet inwards Java? (answer)
10 Java HashMap based Interview Questions alongside Answers (list)
What is the departure betwixt HashMap in addition to LinkedHashMap inwards Java? (answer)
How to variety a Map yesteryear values inwards Java 8? (tutorial)
How to variety an ArrayList using Comparator inwards Java 8? (tutorial)
What is the departure betwixt Iterator in addition to ListIterator inwards Java? (answer)
How to take away elements from HashMap during iteration inwards Java? (answer)

Thanks for reading this article, if y'all similar this article in addition to hence delight percentage alongside your friends in addition to colleagues. If y'all conduct keep whatsoever enquiry or feedback in addition to hence delight drib a comment.

Subscribe to receive free email updates:

0 Response to "How to occupation ConcurrentHashSet from ConcurrentHashMap inwards Java viii - Example Tutorial"

Posting Komentar