Java Reference
In-Depth Information
Performance
ConcurrentHashMap's internal structure was updated to improve performance. Entries of a
map are typically stored in buckets accessed by the generated hashcode of the key. But if many
keys return the same hashcode, performance will deteriorate because buckets are implemented
as Lists with O( n ) retrieval. In Java 8, when the buckets become too big, they're dynamically
replaced with sorted trees, which have O(log( n )) retrieval. Note that this is possible only when
the keys are Comparable (for example, String or Number classes).
Stream-like operations
ConcurrentHashMap supports three new kinds of operations reminiscent of what you saw with
streams:
forEach —Performs a given action for each (key, value)
reduce —Combines all (key, value) given a reduction function into a result
search —Applies a function on each (key, value) until the function produces a non- null result
Each kind of operation supports four forms, accepting functions with keys, values, Map.Entry,
and (key, value) arguments:
Operates with keys and values ( forEach , reduce , search )
Operates with keys ( forEachKey , reduceKeys , searchKeys )
Operates with values ( forEachValue , reduceValues , searchValues )
Operates with Map.Entry objects ( forEachEntry , reduceEntries , searchEntries )
Note that these operations don't lock the state of the ConcurrentHashMap. They operate on the
elements as they go along. The functions supplied to these operations shouldn't depend on any
ordering or on any other objects or values that may change while computation is in progress.
In addition, you need to specify a parallelism threshold for all these operations. The operations
will execute sequentially if the current map size is estimated to be less than the given threshold.
Using a value of 1 enables maximal parallelism using the common thread pool. Using a value of
Long.MAX_VALUE runs the operation on a single thread.
In this example we use the method reduceValues to find the maximum value in the map:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
Optional<Integer> maxValue =
Optional.of(map.reduceValues(1, Integer::max));
 
Search WWH ::




Custom Search