Aracılığıyla paylaş


ConcurrentHashMap Class

Definition

A hash table supporting full concurrency of retrievals and high expected concurrency for updates.

[Android.Runtime.Register("java/util/concurrent/ConcurrentHashMap", DoNotGenerateAcw=true)]
[Java.Interop.JavaTypeParameters(new System.String[] { "K", "V" })]
public class ConcurrentHashMap : Java.Util.AbstractMap, IDisposable, Java.Interop.IJavaPeerable, Java.IO.ISerializable, Java.Util.Concurrent.IConcurrentMap
[<Android.Runtime.Register("java/util/concurrent/ConcurrentHashMap", DoNotGenerateAcw=true)>]
[<Java.Interop.JavaTypeParameters(new System.String[] { "K", "V" })>]
type ConcurrentHashMap = class
    inherit AbstractMap
    interface ISerializable
    interface IJavaObject
    interface IDisposable
    interface IJavaPeerable
    interface IConcurrentMap
    interface IMap
Inheritance
ConcurrentHashMap
Attributes
Implements

Remarks

A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as java.util.Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do <em>not</em> entail locking, and there is <em>not</em> any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently <em>completed</em> update operations holding upon their onset. (More formally, an update operation for a given key bears a <em>happens-before</em> relation with any (non-null) retrieval for that key reporting the updated value.) For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do <em>not</em> throw java.util.ConcurrentModificationException ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time. Bear in mind that the results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads. Otherwise the results of these methods reflect transient states that may be adequate for monitoring or estimation purposes, but not for program control.

The table is dynamically expanded when there are too many collisions (i.e., keys that have distinct hash codes but fall into the same slot modulo the table size), with the expected average effect of maintaining roughly two bins per mapping (corresponding to a 0.75 load factor threshold for resizing). There may be much variance around this average as mappings are added and removed, but overall, this maintains a commonly accepted time/space tradeoff for hash tables. However, resizing this or any other kind of hash table may be a relatively slow operation. When possible, it is a good idea to provide a size estimate as an optional initialCapacity constructor argument. An additional optional loadFactor constructor argument provides a further means of customizing initial table capacity by specifying the table density to be used in calculating the amount of space to allocate for the given number of elements. Also, for compatibility with previous versions of this class, constructors may optionally specify an expected concurrencyLevel as an additional hint for internal sizing. Note that using many keys with exactly the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable, this class may use comparison order among keys to help break ties.

A Set projection of a ConcurrentHashMap may be created (using #newKeySet() or #newKeySet(int)), or viewed (using #keySet(Object) when only keys are of interest, and the mapped values are (perhaps transiently) not used or all take the same mapping value.

A ConcurrentHashMap can be used as a scalable frequency map (a form of histogram or multiset) by using java.util.concurrent.atomic.LongAdder values and initializing via #computeIfAbsent computeIfAbsent. For example, to add a count to a ConcurrentHashMap<String,LongAdder> freqs, you can use freqs.computeIfAbsent(key, k -> new LongAdder()).increment();

This class and its views and iterators implement all of the <em>optional</em> methods of the Map and Iterator interfaces.

Like Hashtable but unlike HashMap, this class does <em>not</em> allow null to be used as a key or value.

ConcurrentHashMaps support a set of sequential and parallel bulk operations that, unlike most Stream methods, are designed to be safely, and often sensibly, applied even with maps that are being concurrently updated by other threads; for example, when computing a snapshot summary of the values in a shared registry. There are three kinds of operation, each with four forms, accepting functions with keys, values, entries, and (key, value) pairs as arguments and/or return values. Because the elements of a ConcurrentHashMap are not ordered in any particular way, and may be processed in different orders in different parallel executions, the correctness of supplied functions should not depend on any ordering, or on any other objects or values that may transiently change while computation is in progress; and except for forEach actions, should ideally be side-effect-free. Bulk operations on Map.Entry objects do not support method setValue.

<ul> <li>forEach: Performs a given action on each element. A variant form applies a given transformation on each element before performing the action.

<li>search: Returns the first available non-null result of applying a given function on each element; skipping further search when a result is found.

<li>reduce: Accumulates each element. The supplied reduction function cannot rely on ordering (more formally, it should be both associative and commutative). There are five variants:

<ul>

<li>Plain reductions. (There is not a form of this method for (key, value) function arguments since there is no corresponding return type.)

<li>Mapped reductions that accumulate the results of a given function applied to each element.

<li>Reductions to scalar doubles, longs, and ints, using a given basis value.

</ul> </ul>

These bulk operations accept a parallelismThreshold argument. Methods proceed sequentially if the current map size is estimated to be less than the given threshold. Using a value of Long.MAX_VALUE suppresses all parallelism. Using a value of 1 results in maximal parallelism by partitioning into enough subtasks to fully utilize the ForkJoinPool#commonPool() that is used for all parallel computations. Normally, you would initially choose one of these extreme values, and then measure performance of using in-between values that trade off overhead versus throughput.

The concurrency properties of bulk operations follow from those of ConcurrentHashMap: Any non-null result returned from get(key) and related access methods bears a happens-before relation with the associated insertion or update. The result of any bulk operation reflects the composition of these per-element relations (but is not necessarily atomic with respect to the map as a whole unless it is somehow known to be quiescent). Conversely, because keys and values in the map are never null, null serves as a reliable atomic indicator of the current lack of any result. To maintain this property, null serves as an implicit basis for all non-scalar reduction operations. For the double, long, and int versions, the basis should be one that, when combined with any other value, returns that other value (more formally, it should be the identity element for the reduction). Most common reductions have these properties; for example, computing a sum with basis 0 or a minimum with basis MAX_VALUE.

Search and transformation functions provided as arguments should similarly return null to indicate the lack of any result (in which case it is not used). In the case of mapped reductions, this also enables transformations to serve as filters, returning null (or, in the case of primitive specializations, the identity basis) if the element should not be combined. You can create compound transformations and filterings by composing them yourself under this "null means there is nothing there now" rule before using them in search or reduce operations.

Methods accepting and/or returning Entry arguments maintain key-value associations. They may be useful for example when finding the key for the greatest value. Note that "plain" Entry arguments can be supplied using new AbstractMap.SimpleEntry(k,v).

Bulk operations may complete abruptly, throwing an exception encountered in the application of a supplied function. Bear in mind when handling such exceptions that other concurrently executing functions could also have thrown exceptions, or would have done so if the first exception had not occurred.

Speedups for parallel compared to sequential forms are common but not guaranteed. Parallel operations involving brief functions on small maps may execute more slowly than sequential forms if the underlying work to parallelize the computation is more expensive than the computation itself. Similarly, parallelization may not lead to much actual parallelism if all processors are busy performing unrelated tasks.

All arguments to all task methods must be non-null.

This class is a member of the Java Collections Framework.

Added in 1.5.

Java documentation for java.util.concurrent.ConcurrentHashMap.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

ConcurrentHashMap()

Creates a new, empty map with the default initial table size (16).

ConcurrentHashMap(IDictionary)

Creates a new map with the same mappings as the given map.

ConcurrentHashMap(Int32, Single, Int32)

Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity), initial table density (loadFactor), and number of concurrently updating threads (concurrencyLevel).

ConcurrentHashMap(Int32, Single)

Creates a new, empty map with an initial table size based on the given number of elements (initialCapacity) and initial table density (loadFactor).

ConcurrentHashMap(Int32)

Creates a new, empty map with an initial table size accommodating the specified number of elements without the need to dynamically resize.

ConcurrentHashMap(IntPtr, JniHandleOwnership)

A constructor used when creating managed representations of JNI objects; called by the runtime.

Properties

Class

Returns the runtime class of this Object.

(Inherited from Object)
Handle

The handle to the underlying Android instance.

(Inherited from Object)
IsEmpty

To be added

(Inherited from AbstractMap)
JniIdentityHashCode (Inherited from Object)
JniPeerMembers
PeerReference (Inherited from Object)
ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Clear()

To be added

(Inherited from AbstractMap)
Clone()

Creates and returns a copy of this object.

(Inherited from Object)
Compute(Object, IBiFunction)

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

ComputeIfAbsent(Object, IFunction)

If the specified key is not already associated with a value, attempts to compute its value using the given mapping function and enters it into this map unless null.

ComputeIfPresent(Object, IBiFunction)

If the value for the specified key is present, attempts to compute a new mapping given the key and its current mapped value.

Contains(Object)

Tests if some key maps into the specified value in this table.

ContainsKey(Object)

To be added

(Inherited from AbstractMap)
ContainsValue(Object)

To be added

(Inherited from AbstractMap)
Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Elements()

Returns an enumeration of the values in this table.

EntrySet()

Returns a Set view of the mappings contained in this map.

Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
ForEach(IBiConsumer)

Performs the given action for each (key, value).

ForEach(Int64, IBiConsumer)

Performs the given action for each (key, value).

ForEach(Int64, IBiFunction, IConsumer)

Performs the given action for each non-null transformation of each (key, value).

ForEachEntry(Int64, IConsumer)

Performs the given action for each entry.

ForEachEntry(Int64, IFunction, IConsumer)

Performs the given action for each non-null transformation of each entry.

ForEachKey(Int64, IConsumer)

Performs the given action for each key.

ForEachKey(Int64, IFunction, IConsumer)

Performs the given action for each non-null transformation of each key.

ForEachValue(Int64, IConsumer)

Performs the given action for each value.

ForEachValue(Int64, IFunction, IConsumer)

Performs the given action for each non-null transformation of each value.

Get(Object)

To be added

(Inherited from AbstractMap)
GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
GetOrDefault(Object, Object)

Returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key.

JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
Keys()

Returns an enumeration of the keys in this table.

KeySet()

To be added

(Inherited from AbstractMap)
MappingCount()

Returns the number of mappings.

Merge(Object, Object, IBiFunction)

If the specified key is not already associated with a (non-null) value, associates it with the given value.

Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
Put(Object, Object)

To be added

(Inherited from AbstractMap)
PutAll(IDictionary)

To be added

(Inherited from AbstractMap)
PutIfAbsent(Object, Object)

To be added

Reduce(Int64, IBiFunction, IBiFunction)

Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values, or null if none.

ReduceEntries(Int64, IBiFunction)

Returns the result of accumulating all entries using the given reducer to combine values, or null if none.

ReduceEntries(Int64, IFunction, IBiFunction)

Returns the result of accumulating the given transformation of all entries using the given reducer to combine values, or null if none.

ReduceEntriesToDouble(Int64, IToDoubleFunction, Double, IDoubleBinaryOperator)

Returns the result of accumulating the given transformation of all entries using the given reducer to combine values, and the given basis as an identity value.

ReduceEntriesToInt(Int64, IToIntFunction, Int32, IIntBinaryOperator)

Returns the result of accumulating the given transformation of all entries using the given reducer to combine values, and the given basis as an identity value.

ReduceEntriesToLong(Int64, IToLongFunction, Int64, ILongBinaryOperator)

Returns the result of accumulating the given transformation of all entries using the given reducer to combine values, and the given basis as an identity value.

ReduceKeys(Int64, IBiFunction)

Returns the result of accumulating all keys using the given reducer to combine values, or null if none.

ReduceKeys(Int64, IFunction, IBiFunction)

Returns the result of accumulating the given transformation of all keys using the given reducer to combine values, or null if none.

ReduceKeysToDouble(Int64, IToDoubleFunction, Double, IDoubleBinaryOperator)

Returns the result of accumulating the given transformation of all keys using the given reducer to combine values, and the given basis as an identity value.

ReduceKeysToInt(Int64, IToIntFunction, Int32, IIntBinaryOperator)

Returns the result of accumulating the given transformation of all keys using the given reducer to combine values, and the given basis as an identity value.

ReduceKeysToLong(Int64, IToLongFunction, Int64, ILongBinaryOperator)

Returns the result of accumulating the given transformation of all keys using the given reducer to combine values, and the given basis as an identity value.

ReduceToDouble(Int64, IToDoubleBiFunction, Double, IDoubleBinaryOperator)

Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values, and the given basis as an identity value.

ReduceToInt(Int64, IToIntBiFunction, Int32, IIntBinaryOperator)

Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values, and the given basis as an identity value.

ReduceToLong(Int64, IToLongBiFunction, Int64, ILongBinaryOperator)

Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values, and the given basis as an identity value.

ReduceValues(Int64, IBiFunction)

Returns the result of accumulating all values using the given reducer to combine values, or null if none.

ReduceValues(Int64, IFunction, IBiFunction)

Returns the result of accumulating the given transformation of all values using the given reducer to combine values, or null if none.

ReduceValuesToDouble(Int64, IToDoubleFunction, Double, IDoubleBinaryOperator)

Returns the result of accumulating the given transformation of all values using the given reducer to combine values, and the given basis as an identity value.

ReduceValuesToInt(Int64, IToIntFunction, Int32, IIntBinaryOperator)

Returns the result of accumulating the given transformation of all values using the given reducer to combine values, and the given basis as an identity value.

ReduceValuesToLong(Int64, IToLongFunction, Int64, ILongBinaryOperator)

Returns the result of accumulating the given transformation of all values using the given reducer to combine values, and the given basis as an identity value.

Remove(Object, Object)

To be added

Remove(Object)

To be added

(Inherited from AbstractMap)
Replace(Object, Object, Object)

To be added

Replace(Object, Object)

To be added

ReplaceAll(IBiFunction)
Search(Int64, IBiFunction)

Returns a non-null result from applying the given search function on each (key, value), or null if none.

SearchEntries(Int64, IFunction)

Returns a non-null result from applying the given search function on each entry, or null if none.

SearchKeys(Int64, IFunction)

Returns a non-null result from applying the given search function on each key, or null if none.

SearchValues(Int64, IFunction)

Returns a non-null result from applying the given search function on each value, or null if none.

SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
Size()

To be added

(Inherited from AbstractMap)
ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
Values()

To be added

(Inherited from AbstractMap)
Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Applies to