A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not 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 completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before 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 not throw 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 scalable frequency map (a form of histogram or multiset) by using java.util.concurrent.atomic.LongAdder values and initializing via computeIfAbsent. For example, to add a count to a ConcurrentHashMap<String,LongAdder> freqs, you can use freqs.computeIfAbsent(k -> new LongAdder()).increment();
This class and its views and iterators implement all of the optional methods of the Map and Iterator interfaces.
Like Hashtable but unlike HashMap, this class does not 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) 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.
forEach: Perform a given action on each element. A variant form applies a given transformation on each element before performing the action.
search: Return the first available non-null result of applying a given function on each element; skipping further search when a result is found.
reduce: Accumulate each element. The supplied reduction function cannot rely on ordering (more formally, it should be both associative and commutative). There are five variants:
Plain reductions. (There is not a form of this method for (key, value) function arguments since there is no corresponding return type.)
Mapped reductions that accumulate the results of a given function applied to each element.
Reductions to scalar doubles, longs, and ints, using a given basis value.
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.
一种哈希表,支持检索的完全并发性和更新的高预期并发性。这个类遵循与Hashtable相同的函数规范,并且包含与Hashtable的每个方法对应的方法版本。但是,即使所有操作都是线程安全的,检索操作也不需要锁定,并且不支持以阻止所有访问的方式锁定整个表。此类在依赖于其线程安全性而不依赖于其同步细节的程序中与哈希表完全互操作。
检索操作(包括get)通常不阻塞,因此可能与更新操作(包括put和remove)重叠。检索反映了最近完成的更新操作在开始时的结果。(更正式地说,给定键的更新操作与报告更新值的该键的任何(非空)检索具有“发生在”关系。)对于聚合操作(如putAll和clear),并发检索可能只反映插入或删除某些条目。类似地,迭代器、拆分器和枚举返回反映哈希表在创建迭代器/枚举时或之后某个点的状态的元素。它们不会抛出ConcurrentModificationException。但是,迭代器设计为一次只能由一个线程使用。请记住,聚合状态方法(包括size、isEmpty和containsValue)的结果通常仅在映射没有在其他线程中进行并发更新时才有用。否则,这些方法的结果反映的瞬态可能足以用于监视或估计目的,但不足以用于程序控制。
当冲突太多时(即,具有不同哈希码但落在表大小的同一插槽中的键),表将动态展开,预期的平均效果是每个映射保持大约两个存储箱(对应于0.75的负载因子阈值,用于调整大小)。随着映射的添加和删除,这个平均值可能会有很大的差异,但总的来说,这为哈希表保持了一个普遍接受的时间/空间权衡。但是,调整此哈希表或任何其他类型的哈希表的大小可能是一个相对缓慢的操作。如果可能,最好提供一个大小估计值作为可选的initialCapacity构造函数参数。另外一个可选的loadFactor构造函数参数提供了一种定制初始表容量的方法,它指定了在计算为给定数量的元素分配的空间量时要使用的表密度。此外,为了与此类的早期版本兼容,构造函数可以选择指定预期的concurrencyLevel作为内部大小调整的附加提示。请注意,使用具有完全相同hashCode()的多个键肯定会降低任何哈希表的性能。为了改善影响,当键具有可比性时,此类可以使用键之间的比较顺序来帮助打破联系。
ConcurrentHashMap的集合投影可以创建(使用newKeySet()或newKeySet(int)),或者查看(使用keySet(Object),当只有键是感兴趣的,并且映射的值(可能是暂时的)没有被使用或者全部取相同的映射值时。
ConcurrentHashMap可以通过使用java.util.concurrent文件.原子长加法器值并通过ComputeFabSent初始化。例如,要向ConcurrentHashMap<String,LongAdder>freqs添加计数,可以使用发送频率(k->new LongAdder()).increment();
这个类及其视图和迭代器实现了Map和迭代器接口的所有可选方法。
与Hashtable类似,但与HashMap不同,此类不允许将null用作键或值。
ConcurrentHashMaps支持一组顺序和并行批量操作,与大多数流方法不同,这些操作被设计为安全且通常是合理地应用于其他线程同时更新的映射;例如,在计算共享注册表中值的快照摘要时。有三种操作,每种都有四种形式,接受带有键、值、条目和(键、值)参数和/或返回值的函数。因为ConcurrentHashMap的元素不是以任何特定的方式排序的,并且可以在不同的并行执行中以不同的顺序进行处理,所以提供的函数的正确性不应该依赖于任何排序,或者依赖于任何其他对象或值,这些对象或值在计算过程中可能会瞬间改变;并且除了forEach最好是没有副作用。批量操作地图输入对象不支持方法setValue。
forEach:对每个元素执行给定的操作。变量形式在执行操作之前对每个元素应用给定的转换。
搜索:返回在每个元素上应用给定函数的第一个可用的非空结果
网友评论