How To Practise A Thread-Safe Concurrenthashset Inwards Coffee 8? Example
Until JDK 8, in that place was no means to exercise a large, thread-safe, ConcurrentHashSet inward Java. The java.util.concurrent packet doesn't fifty-fifty receive got a course of report called ConcurrentHashSet, but from JDK 8 onwards, you lot tin hand the sack usage the newly added keySet(default value) in addition to newKeySet() methods to exercise a ConcurrentHashSet backed yesteryear ConcurrentHashMap inward Java. This is amend than former tactical solutions similar using a concurrent hash map amongst dummy value or using the laid upward sentiment of the map, where you lot cannot add together novel elements. The Set returned yesteryear keySet(defaultValue) in addition to newKeySet() methods of JDK 8 is a proper set, where you lot tin hand the sack equally good add together novel elements along amongst performing other laid upward operations e.g. contains(), remove() etc.
Though you lot need to last a petty fighting careful because these methods are solely available inward ConcurrentHashMap course of report in addition to non inward ConcurrentMap interface, thus you lot need to usage a ConcurrentHashMap reference variable to concur the reference, or you lot need to usage 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 acquire to a greater extent than well-nigh changes inward Java 8, I propose you lot convey a seem at CopyOnArrayList for ArrayList, ConcurrentHahsMap for HashMap in addition to CopyOnWriteArraySet for HashSet, but in that place is zero similar ConcurrentHashSet inward Java.
Even though, CopyOnWriteArraySet is thread-safe it is non suitable for application where you lot need a large thread-safe set. It is solely used for application where laid upward sizes remain small-scale in addition to read-only operations vastly outnumber write operations.
So, when you lot enquire Java programmers well-nigh how to exercise ConcurrentHashSet without writing their ain class, many volition country that they tin hand the sack usage ConcurrentHashMap amongst same values. This is inward fact what Java equally good does to exercise HashSet. If you lot receive got 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 receive got a map in addition to non set. You cannot perform laid upward operations on your ConcurrentHashMap amongst dummy values. You cannot transcend it some when some method expects a Set, thus it's non really usable.
The other option, many Java programmer volition shout that you lot tin hand the sack acquire a Set sentiment from ConcurrentHashMap yesteryear calling the keySet() method, which inward fact furnish a Set, where you lot tin hand the sack perform Set operations in addition to transcend it some to a method which expects a Set but this approach equally good has its limitation.
For example, the Set is backed yesteryear ConcurrentHashMap in addition to whatever modify inward Map volition reverberate inward Set equally well. Another limitation was that you lot cannot add together novel elements into this telephone substitution set, doing thus volition throw UnsupportedOperationException.
If you lot are non familiar well-nigh this exception, I propose you lot join The Complete Java MasterClass - Updated for Java 11, i of the best resources to acquire 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 sentiment returned from the keySet() method, you lot tin hand the sack equally good add together novel objects into this Set. The method is equally good overloaded in addition to accepts an initial capacity to foreclose resizing of Set.
Btw, this is not the solely way to exercise a concurrent, large, thread-safe Set inward Java.
You tin hand the sack equally good usage the newly added, overloaded keySet(default value) method to exercise a ConcurrentHashSet. This method returns a Set sentiment 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 course of report solely usage you lot tin hand the sack usage the same value for all elements inward the Set, which is Ok inward most situations because you lot don't actually tending well-nigh values inward Set. Remember, HashSet is equally good 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 receive got commented that code, but, Set returned yesteryear newKeySet() in addition to 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 solely means to exercise a thread-safe Set inward Java. Even earlier Java 8, in that place is a course of report called CopyOnWriteArraySet which allows you lot to exercise a thread-safe laid upward inward Java.
It is similar to CopyOnWriteArrayList in addition to solely suitable for application where laid upward size is small-scale in addition to you lot solely exercise read the solely 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 acquire to a greater extent than well-nigh concurrent collections inward Java 8.
Here are some of the of import properties of CopyOnWriteArraySet:
1. It is best suited for applications inward which laid upward sizes to a greater extent than ofttimes than non remain small, read-only operations vastly outnumber mutative operations, in addition to you lot need to foreclose interference amid threads during traversal.
That's all well-nigh how to exercise ConcurrentHashSet inward Java 8. The JDK 8 API non solely has major features similar lambda seem in addition to current but equally good these kinds of small-scale changes which brand your solar daytime to solar daytime coding easier. It's non super slowly to exercise a ConcurrentHashSet inward Java using the newKeySet() method.
You don't need to usage a map similar a laid upward amongst a bogus value or alive amongst the limitation of laid upward 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 in addition to 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 usage forEach() method inward Java 8 (example) How to usage filter() method inward Java 8 (tutorial) 10 examples of Optionals in Java 8? (example) How to usage Stream course of report inward Java 8 (tutorial) How to usage peek() method inward Java 8 (example) How to convert List to Map inward Java 8 (solution) How to format/parse the engagement amongst LocalDateTime inward Java 8? (tutorial) How to sort the map yesteryear keys inward Java 8? (example) 10 Java 8 Stream in addition to Functional Programming Interview Questions (answers) How to usage findFirst() method of Stream inward Java 8 (example) Java 8 map + filter + collect + current trial (tutorial)
Thanks for reading this article thus far. If you lot similar this article thus delight portion amongst your friends in addition to colleagues. If you lot receive got whatever enquiry or feedback thus delight drib a comment.
P. S. - If you lot don't heed learning from gratis resources thus you lot tin hand the sack equally good banking concern gibe out this listing of free Java 8 in addition to Java ix courses to acquire better.
P. P. S. - If you lot similar to acquire from books then Java 8 inward Action is the best mass to acquire both Java 8 features equally good equally other API enhancements made inward JDK 8.
Though you lot need to last a petty fighting careful because these methods are solely available inward ConcurrentHashMap course of report in addition to non inward ConcurrentMap interface, thus you lot need to usage a ConcurrentHashMap reference variable to concur the reference, or you lot need to usage 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 acquire to a greater extent than well-nigh changes inward Java 8, I propose you lot convey a seem at CopyOnArrayList for ArrayList, ConcurrentHahsMap for HashMap in addition to CopyOnWriteArraySet for HashSet, but in that place is zero similar ConcurrentHashSet inward Java.
Even though, CopyOnWriteArraySet is thread-safe it is non suitable for application where you lot need a large thread-safe set. It is solely used for application where laid upward sizes remain small-scale in addition to read-only operations vastly outnumber write operations.
So, when you lot enquire Java programmers well-nigh how to exercise ConcurrentHashSet without writing their ain class, many volition country that they tin hand the sack usage ConcurrentHashMap amongst same values. This is inward fact what Java equally good does to exercise HashSet. If you lot receive got 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 receive got a map in addition to non set. You cannot perform laid upward operations on your ConcurrentHashMap amongst dummy values. You cannot transcend it some when some method expects a Set, thus it's non really usable.
The other option, many Java programmer volition shout that you lot tin hand the sack acquire a Set sentiment from ConcurrentHashMap yesteryear calling the keySet() method, which inward fact furnish a Set, where you lot tin hand the sack perform Set operations in addition to transcend it some to a method which expects a Set but this approach equally good has its limitation.
For example, the Set is backed yesteryear ConcurrentHashMap in addition to whatever modify inward Map volition reverberate inward Set equally well. Another limitation was that you lot cannot add together novel elements into this telephone substitution set, doing thus volition throw UnsupportedOperationException.
If you lot are non familiar well-nigh this exception, I propose you lot join The Complete Java MasterClass - Updated for Java 11, i of the best resources to acquire 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 sentiment returned from the keySet() method, you lot tin hand the sack equally good add together novel objects into this Set. The method is equally good overloaded in addition to accepts an initial capacity to foreclose resizing of Set.
1. 1 ConcurrentHashSet using newKeySet() inward Java 8
Here is a code trial to exercise ConcurrentHashSet inward Java 8:ConcurrentHashMap<String, 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 solely way to exercise a concurrent, large, thread-safe Set inward Java.
You tin hand the sack equally good usage the newly added, overloaded keySet(default value) method to exercise a ConcurrentHashSet. This method returns a Set sentiment 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 course of report solely usage you lot tin hand the sack usage the same value for all elements inward the Set, which is Ok inward most situations because you lot don't actually tending well-nigh values inward Set. Remember, HashSet is equally good 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 receive got commented that code, but, Set returned yesteryear newKeySet() in addition to 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 solely means to exercise a thread-safe Set inward Java. Even earlier Java 8, in that place is a course of report called CopyOnWriteArraySet which allows you lot to exercise a thread-safe laid upward inward Java.
It is similar to CopyOnWriteArrayList in addition to solely suitable for application where laid upward size is small-scale in addition to you lot solely exercise read the solely 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 acquire to a greater extent than well-nigh concurrent collections inward Java 8.
Here are some of the of import properties of CopyOnWriteArraySet:
1. It is best suited for applications inward which laid upward sizes to a greater extent than ofttimes than non remain small, read-only operations vastly outnumber mutative operations, in addition to you lot need to foreclose interference amid threads during traversal.
2. It is thread-safe.
3. Mutative operations (add, set, remove, etc.) are expensive since they ordinarily entail copying the entire underlying array.
4. Iterators exercise non back upward the mutative take away operation.
5. Traversal via iterators is fast in addition to 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 well-nigh how to exercise ConcurrentHashSet inward Java 8. The JDK 8 API non solely has major features similar lambda seem in addition to current but equally good these kinds of small-scale changes which brand your solar daytime to solar daytime coding easier. It's non super slowly to exercise a ConcurrentHashSet inward Java using the newKeySet() method.
You don't need to usage a map similar a laid upward amongst a bogus value or alive amongst the limitation of laid upward sentiment returned by keySet() which doesn't allow you lot to add together novel elements into the Set.
Further Learning
courses)
Thanks for reading this article thus far. If you lot similar this article thus delight portion amongst your friends in addition to colleagues. If you lot receive got whatever enquiry or feedback thus delight drib a comment.
P. S. - If you lot don't heed learning from gratis resources thus you lot tin hand the sack equally good banking concern gibe out this listing of free Java 8 in addition to Java ix courses to acquire better.
P. P. S. - If you lot similar to acquire from books then Java 8 inward Action is the best mass to acquire both Java 8 features equally good equally other API enhancements made inward JDK 8.


Komentar
Posting Komentar