How To Utilisation A Thread-Safe Concurrenthashset Inward Coffee 8? Example

Advertisement

Masukkan script iklan 970x90px

How To Utilisation A Thread-Safe Concurrenthashset Inward Coffee 8? Example

Jumat, 27 Maret 2020

Until JDK 8, in that place was no agency to exercise a large, thread-safe, ConcurrentHashSet inward Java. The java.util.concurrent bundle doesn't fifty-fifty direct maintain a class 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 inward Java. This is ameliorate than erstwhile tactical solutions similar using a concurrent hash map amongst dummy value or using the ready stance 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 likewise add together novel elements along amongst performing other ready operations e.g. contains(), remove() etc.

Though you lot ask to hold upward a picayune fighting careful because these methods are entirely available inward ConcurrentHashMap class together with non inward ConcurrentMap interface, thus you lot ask to utilisation a ConcurrentHashMap reference variable to agree the reference, or you lot ask to utilisation type casting to cast a ConcurrentHashMap object stored inward ConcurrentMap variable.

Btw, this is i of the many useful library enhancement acquaint inward JDK 8. If you lot desire to larn to a greater extent than virtually changes inward Java 8, I propose you lot convey a appear at CopyOnArrayList for ArrayList, ConcurrentHahsMap for HashMap together with CopyOnWriteArraySet for HashSet, but in that place is nix similar ConcurrentHashSet inward Java.

Even though, CopyOnWriteArraySet is thread-safe it is non suitable for application where you lot ask a large thread-safe set. It is entirely used for application where ready sizes remain pocket-sized together with read-only operations vastly outnumber write operations.

So, when you lot inquire Java programmers virtually how to exercise ConcurrentHashSet without writing their ain class, many volition tell that they tin utilisation ConcurrentHashMap amongst same values. This is inward fact what Java likewise does to exercise HashSet. If you lot direct maintain read my article how HashSet internally plant inward Java, you lot may retrieve that HashSet internally uses HashMap amongst the same values.



But, the work amongst this approach is that you lot direct maintain a map together with non set. You cannot perform ready operations on your ConcurrentHashMap amongst dummy values. You cannot overstep it only about when some method expects a Set, thus it's non rattling usable.


The other option, many Java programmer volition advert that you lot tin acquire a Set stance from ConcurrentHashMap yesteryear calling the keySet() method, which inward fact supply a Set, where you lot tin perform Set operations together with 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 together with whatever alter inward Map volition reverberate inward Set every bit well. Another limitation was that you lot cannot add together novel elements into this cardinal set, doing thus volition throw UnsupportedOperationException

If you lot are non familiar virtually 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 right away 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 stance returned from the keySet() method, you lot tin likewise add together novel objects into this Set. The method is likewise overloaded together with accepts an initial capacity to forestall resizing of Set.

1. 1 ConcurrentHashSet using newKeySet() inward Java 8

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

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


This is of class entirely utilisation you lot tin utilisation the same value for all elements inward the Set, which is Ok inward most situations because you lot don't actually attention virtually values inward Set. Remember, HashSet is likewise 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 inward 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 direct maintain 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, in that place is no mistake there.


By the way, this is non the entirely agency to exercise a thread-safe Set inward Java. Even earlier Java 8, in that place is a class called CopyOnWriteArraySet which allows you lot to exercise a thread-safe ready inward Java.

It is similar to CopyOnWriteArrayList together with entirely suitable for application where ready size is pocket-sized together with you lot entirely exercise read the entirely 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 virtually concurrent collections inward Java 8.

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


Here are some of the of import properties of CopyOnWriteArraySet:

1. It is best suited for applications inward which ready sizes by together with large remain small, read-only operations vastly outnumber mutative operations, together with you lot ask to forestall interference amid 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 exercise non back upward the mutative take operation.

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

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


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

You don't ask to utilisation a map similar a ready amongst a bogus value or alive amongst the limitation of ready stance 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 inward Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to bring together String inward Java 8 (example)
  • How to utilisation forEach() method inward Java 8 (example)
  • How to utilisation filter() method inward Java 8 (tutorial)
  • 10 examples of Optionals in Java 8? (example)
  • How to utilisation Stream class inward Java 8 (tutorial)
  • How to utilisation peek() method inward Java 8 (example)
  • How to convert List to Map inward Java 8 (solution)
  • How to format/parse the appointment amongst LocalDateTime inward Java 8? (tutorial)
  • How to sort the map yesteryear keys inward Java 8? (example)
  • 10 Java 8 Stream together with Functional Programming Interview Questions (answers)
  • How to utilisation findFirst() method of Stream inward Java 8 (example)
  • Java 8 map + filter + collect + flow lawsuit (tutorial)

  • Thanks for reading this article thus far. If you lot similar this article together with thus delight portion amongst your friends together with colleagues. If you lot direct maintain whatever enquiry or feedback together with thus delight drib a comment.


    P. S. - If you lot don't hear learning from gratis resources together with thus you lot tin likewise banking concern fit 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 inward Action is the best mass to larn both Java 8 features every bit good every bit other API enhancements made inward JDK 8.