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

Until JDK 8, at that spot was no agency to exercise a large, thread-safe, ConcurrentHashSet inwards Java. The java.util.concurrent packet doesn't fifty-fifty receive got a course of written report called ConcurrentHashSet, but from JDK 8 onwards, you lot tin utilisation the newly added keySet(default value) together with newKeySet() methods to exercise a ConcurrentHashSet backed yesteryear ConcurrentHashMap inwards Java. This is ameliorate than onetime tactical solutions similar using a concurrent hash map amongst dummy value or using the fix sentiment of the map, where you lot cannot add together novel elements. The Set returned yesteryear keySet(defaultValue) together with newKeySet() methods of JDK 8 is a proper set, where you lot tin too add together novel elements along amongst performing other fix operations e.g. contains(), remove() etc.

Though you lot postulate to last a footling fighting careful because these methods are alone available inwards ConcurrentHashMap course of written report together with non inwards ConcurrentMap interface, thence you lot postulate to utilisation a ConcurrentHashMap reference variable to concord the reference, or you lot postulate to utilisation type casting to cast a ConcurrentHashMap object stored inwards ConcurrentMap variable.

Btw, this is ane of the many useful library enhancement introduce inwards JDK 8. If you lot desire to larn to a greater extent than most changes inwards Java 8, I advise you lot convey a appear at CopyOnArrayList for ArrayList, ConcurrentHahsMap for HashMap together with CopyOnWriteArraySet for HashSet, but at that spot is nada similar ConcurrentHashSet inwards Java.

Even though, CopyOnWriteArraySet is thread-safe it is non suitable for application where you lot postulate a large thread-safe set. It is alone used for application where fix sizes rest pocket-size together with read-only operations vastly outnumber write operations.

So, when you lot inquire Java programmers most how to exercise ConcurrentHashSet without writing their ain class, many volition tell that they tin utilisation ConcurrentHashMap amongst same values. This is inwards fact what Java too does to exercise HashSet. If you lot receive got read my article how HashSet internally industrial plant inwards Java, you lot may recollect that HashSet internally uses HashMap amongst the same values.



But, the employment amongst this approach is that you lot receive got a map together with non set. You cannot perform fix operations on your ConcurrentHashMap amongst dummy values. You cannot exceed it roughly when some method expects a Set, thence it's non really usable.


The other option, many Java programmer volition cite that you lot tin acquire a Set sentiment from ConcurrentHashMap yesteryear calling the keySet() method, which inwards fact provide a Set, where you lot tin perform Set operations together with exceed it roughly to a method which expects a Set but this approach too has its limitation.

For example,  the Set is backed yesteryear ConcurrentHashMap together with 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 most this exception, I advise you lot join The Complete Java MasterClass - Updated for Java 11, ane of the best resources to larn Java yesteryear yourself.



Anyway, both of these limitations are directly affair 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 sentiment returned from the keySet() method, you lot tin too add together novel objects into this Set. The method is too overloaded together with accepts an initial capacity to forestall resizing of Set.

1. 1 ConcurrentHashSet using newKeySet() inwards Java 8

Here is a code lawsuit to exercise 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 exercise a concurrent, large, thread-safe Set inwards Java.

You tin too utilisation the newly added, overloaded keySet(default value) method to exercise a ConcurrentHashSet.  This method returns a Set sentiment 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 course of written report alone utilisation you lot tin utilisation the same value for all elements inwards the Set, which is Ok inwards most situations because you lot don't actually assist most values inwards Set. Remember, HashSet is too a HashMap amongst 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 receive got commented that code, but, Set returned yesteryear newKeySet() together with keySet(mapped value) methods allows you lot to add together novel elements into the Set, at that spot is no mistake there.


By the way, this is non the alone agency to exercise a thread-safe Set inwards Java. Even earlier Java 8, at that spot is a course of written report called CopyOnWriteArraySet which allows you lot to exercise a thread-safe fix inwards Java.

It is similar to CopyOnWriteArrayList together with alone suitable for application where fix size is pocket-size together with you lot alone exercise read the alone functioning 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 most concurrent collections inwards Java 8.

 This is ameliorate than onetime tactical solutions similar using a concurrent hash map amongst 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 fix sizes to a greater extent than oft than non rest small, read-only operations vastly outnumber mutative operations, together with you lot postulate to forestall interference amid threads during traversal.

2. It is thread-safe.

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

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

5. Traversal via iterators is fast together with cannot watch interference from other threads.

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


That's all most how to exercise ConcurrentHashSet inwards Java 8. The JDK 8 API non alone has major features similar lambda facial expression together with flow but too these kinds of pocket-size changes which brand your hateful solar daytime to hateful solar daytime coding easier. It's non super slow to exercise a ConcurrentHashSet inwards Java using the newKeySet() method.

You don't postulate to utilisation a map similar a fix amongst a bogus value or alive amongst the limitation of fix sentiment returned by keySet() which doesn't allow you lot to add together novel elements into the Set.

Further Learning
courses)
  • 20 Examples of Date together with 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 utilisation forEach() method inwards Java 8 (example)
  • How to utilisation filter() method inwards Java 8 (tutorial)
  • 10 examples of Optionals in Java 8? (example)
  • How to utilisation Stream course of written report inwards Java 8 (tutorial)
  • How to utilisation peek() method inwards Java 8 (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to format/parse the engagement amongst LocalDateTime inwards Java 8? (tutorial)
  • How to sort the map yesteryear keys inwards Java 8? (example)
  • 10 Java 8 Stream together with Functional Programming Interview Questions (answers)
  • How to utilisation 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 thence delight portion amongst your friends together with colleagues. If you lot receive got whatever enquiry or feedback thence delight drib a comment.


    P. S. - If you lot don't heed learning from complimentary resources thence you lot tin too depository fiscal establishment stand upwards for out this listing of free Java 8 together with 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.


    Sumber https://javarevisited.blogspot.com/

    0 Response to "How To Usage 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