How To Practise A Thread-Safe Concurrenthashset Inwards Coffee 8? Example

Until JDK 8, at that topographic point was no agency to practice a large, thread-safe, ConcurrentHashSet inwards Java. The java.util.concurrent packet doesn't fifty-fifty conduct maintain a cast called ConcurrentHashSet, but from JDK 8 onwards, you lot tin utilization the newly added keySet(default value) as well as newKeySet() methods to practice a ConcurrentHashSet backed yesteryear ConcurrentHashMap inwards Java. This is ameliorate than former tactical solutions similar using a concurrent hash map with dummy value or using the gear upwards persuasion of the map, where you lot cannot add together novel elements. The Set returned yesteryear keySet(defaultValue) as well as newKeySet() methods of JDK 8 is a proper set, where you lot tin likewise add together novel elements along with performing other gear upwards operations e.g. contains(), remove() etc.

Though you lot take to hold upwards a trivial flake careful because these methods are alone available inwards ConcurrentHashMap cast as well as non inwards ConcurrentMap interface, thence you lot take to utilization a ConcurrentHashMap reference variable to concur the reference, or you lot take to utilization type casting to cast a ConcurrentHashMap object stored inwards ConcurrentMap variable.

Btw, this is i of the many useful library enhancement acquaint inwards JDK 8. If you lot desire to larn to a greater extent than close changes inwards Java 8, I propose you lot convey a appear at CopyOnArrayList for ArrayList, ConcurrentHahsMap for HashMap as well as CopyOnWriteArraySet for HashSet, but at that topographic point is zip similar ConcurrentHashSet inwards Java.

Even though, CopyOnWriteArraySet is thread-safe it is non suitable for application where you lot take a large thread-safe set. It is alone used for application where gear upwards sizes remain pocket-size as well as read-only operations vastly outnumber write operations.

So, when you lot inquire Java programmers close how to practice ConcurrentHashSet without writing their ain class, many volition tell that they tin utilization ConcurrentHashMap with same values. This is inwards fact what Java likewise does to practice HashSet. If you lot conduct maintain read my article how HashSet internally industrial plant inwards Java, you lot may holler upwards that HashSet internally uses HashMap with the same values.



But, the work with this approach is that you lot conduct maintain a map as well as non set. You cannot perform gear upwards operations on your ConcurrentHashMap with dummy values. You cannot overstep it only about when some method expects a Set, thence it's non really usable.


The other option, many Java programmer volition holler that you lot tin acquire a Set persuasion from ConcurrentHashMap yesteryear calling the keySet() method, which inwards fact provide a Set, where you lot tin perform Set operations as well as overstep it only about to a method which expects a Set but this approach likewise has its limitation.

For example,  the Set is backed yesteryear ConcurrentHashMap as well as whatever modify inwards Map volition reverberate inwards Set every bit well. Another limitation was that you lot cannot add together novel elements into this fundamental set, doing thence volition throw UnsupportedOperationException

If you lot are non familiar close this exception, I propose you lot join The Complete Java MasterClass - Updated for Java 11, i of the best resources to larn Java yesteryear yourself.



Anyway, both of these limitations are directly matter of yesteryear because JDK 8 has added newKeySet() method which returns a Set backed yesteryear a ConcurrentHashMap from the given type where values are Boolean.TRUE.

Unlike Set persuasion returned from the keySet() method, you lot tin likewise add together novel objects into this Set. The method is likewise overloaded as well as accepts an initial capacity to forestall resizing of Set.

1. 1 ConcurrentHashSet using newKeySet() inwards Java 8

Here is a code lawsuit to practice ConcurrentHashSet inwards Java 8:

ConcurrentHashMap&ltString, Integer> certificationCosts = new ConcurrentHashMap<>(); Set<String> concurrentHashSet = certificationCosts.newKeySet(); concurrentHashSet.add("OCEJWCD"); //OK concurrentHashSet.contains("OCEJWCD"); //OK concurrentHashSet.remove("OCEJWCD"); //OK


Btw, this is not the alone way to practice a concurrent, large, thread-safe Set inwards Java.

You tin likewise utilization the newly added, overloaded keySet(default value) method to practice a ConcurrentHashSet.  This method returns a Set persuasion of the keys inwards the ConcurrentHashMap, using the given mutual default value for whatever additions (i.e., Collection.add() and Collection.addAll(Collection)).


This is of class alone utilization you lot tin utilization the same value for all elements inwards the Set, which is Ok inwards most situations because you lot don't actually help close values inwards Set. Remember, HashSet is likewise a HashMap with the same values for all elements, See Set returned yesteryear the keySet() method of ConcurrentHashMap, it throws UnsupportedOperationExcepiton as shown below:


Exception inwards thread "main" java.lang.UnsupportedOperationException
at java.util.concurrent.ConcurrentHashMap$KeySetView.add(ConcurrentHashMap.java:4594)
at Demo.main(Demo.java:23)

That's why I conduct maintain commented that code, but, Set returned yesteryear newKeySet() as well as keySet(mapped value) methods allows you lot to add together novel elements into the Set, at that topographic point is no fault there.


By the way, this is non the alone agency to practice a thread-safe Set inwards Java. Even earlier Java 8, at that topographic point is a cast called CopyOnWriteArraySet which allows you lot to practice a thread-safe gear upwards inwards Java.

It is similar to CopyOnWriteArrayList as well as alone suitable for application where gear upwards size is pocket-size as well as you lot alone practice read the alone performance because it copies all elements from Set to a novel Set every fourth dimension you lot write into it. See Java SE 8 for the Really Impatient to larn to a greater extent than close concurrent collections inwards Java 8.

 This is ameliorate than former tactical solutions similar using a concurrent hash map with dummy va How to Create a thread-safe ConcurrentHashSet inwards Java 8? Example


Here are some of the of import properties of CopyOnWriteArraySet:

1. It is best suited for applications inwards which gear upwards sizes to a greater extent than oft than non remain small, read-only operations vastly outnumber mutative operations, as well as you lot take to forestall interference with threads during traversal.

2. It is thread-safe.

3. Mutative operations (add, set, remove, etc.) are expensive since they commonly entail copying the entire underlying array.

4. Iterators practice non back upwards the mutative take away operation.

5. Traversal via iterators is fast as well as cannot come across interference from other threads.

6. Iterators rely on unchanging snapshots of the array at the fourth dimension the iterators were constructed. 


That's all close how to practice ConcurrentHashSet inwards Java 8. The JDK 8 API non alone has major features similar lambda facial expression as well as flow but likewise these kinds of pocket-size changes which brand your twenty-four hours to twenty-four hours coding easier. It's non super slow to practice a ConcurrentHashSet inwards Java using the newKeySet() method.

You don't take to utilization a map similar a gear upwards with a bogus value or alive with the limitation of gear upwards persuasion returned by keySet() which doesn't allow you lot to add together novel elements into the Set.

Further Learning
courses)
  • 20 Examples of Date as well as Time inwards Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to bring together String inwards Java 8 (example)
  • How to utilization forEach() method inwards Java 8 (example)
  • How to utilization filter() method inwards Java 8 (tutorial)
  • 10 examples of Optionals in Java 8? (example)
  • How to utilization Stream cast inwards Java 8 (tutorial)
  • How to utilization peek() method inwards Java 8 (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to format/parse the appointment with LocalDateTime inwards Java 8? (tutorial)
  • How to sort the map yesteryear keys inwards Java 8? (example)
  • 10 Java 8 Stream as well as Functional Programming Interview Questions (answers)
  • How to utilization findFirst() method of Stream inwards Java 8 (example)
  • Java 8 map + filter + collect + flow lawsuit (tutorial)

  • Thanks for reading this article thence far. If you lot similar this article as well as then delight part with your friends as well as colleagues. If you lot conduct maintain whatever enquiry or feedback as well as then delight drib a comment.


    P. S. - If you lot don't heed learning from gratis resources as well as then you lot tin likewise cheque out this listing of free Java 8 as well as Java ix courses to larn better.

    P.  P. S. - If you lot similar to larn from books then Java 8 inwards Action is the best majority to larn both Java 8 features every bit good every bit other API enhancements made inwards JDK 8.

    0 Response to "How To Practise A Thread-Safe Concurrenthashset Inwards Coffee 8? Example"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel