源码阅读 - ConcurrentHashMap类注释

ConcurrentHashMap源码build 1.8.0_121-b13版本类注释

/**
 * A hash table supporting full concurrency of retrievals and
 * high expected concurrency for updates. This class obeys the
 * same functional specification as {@link java.util.Hashtable}, and
 * includes versions of methods corresponding to each method of
 * {@code 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 {@code Hashtable} in programs that rely on its
 * thread safety but not on its synchronization details.
 * 一个支持全并发检索和高并发更新的哈希表,本类和Hashtable遵循相同的功能规范,并且包含了HashTable的每个方法的并发版本。
 * 然而,即使所有操作都是线程安全的,检索操作不需要上锁,也没有任何方法支持整表锁定来阻止对表的任何访问。
 * 在依赖此类的线程安全性而不是同步性的程序中,可以和HashTable协同使用。
 * 
 * 

Retrieval operations (including {@code get}) generally do not * block, so may overlap with update operations (including {@code put} * and {@code 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 {@code putAll} and {@code 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 {@link * 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 * {@code size}, {@code isEmpty}, and {@code 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. * 检索操作(例如get)通常是不加锁的,因此可能和更新操作(例如put/remove)同时发生。 * 检索反映了最近一次完成的更新的结果(更正式的说,对于给定Key的任何非空检索和其值的更新具有happens-before关系) * 对于集合操作,例如putAll和clear,并发检索可能只是反映插入或者删除的部分值。 * 同样的Iterators,Spliterators和Enumerations也只是反映了他们创建时hash table的状态。他们并不会抛出ConcurrentModificationException异常。 * 总的来说,遍历器设计的初衷是同一时间只给一个线程使用。 * 牢记一点,反映集合状态的操作(例如size,isEmpty和containsValue)的返回值通常只有在该集合没有在其他线程并发更新时才是有用的。 * 否则这些方法的结果只能反映集合的瞬时状态,仅作为监控或者预估作用,不要用于流程控制。 * *

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 {@code * initialCapacity} constructor argument. An additional optional * {@code 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 {@code concurrencyLevel} as an additional hint for * internal sizing. Note that using many keys with exactly the same * {@code hashCode()} is a sure way to slow down performance of any * hash table. To ameliorate impact, when keys are {@link Comparable}, * this class may use comparison order among keys to help break ties. * 表的每一个位置预期平均存放2个映射关系(相应的,扩容的阈值为容量的0.75),当存放的元素过多时,表格会动态扩展(例如,拥有不同哈希值的key对表的长度取模后落在同一位置) * 随着表中元素的添加和删除,这个平均值可能会有一定变化,但是总的来说还是维持在时间/空间消耗可以普遍接受的。 * 然而,对于ConcurrentHashMap或者其他任何种类的哈希表来说,扩容是一个相对较慢的操作。如果大小可以预估的话,最好在构造函数中指定initialCapacity。 * 构造函数的另一个可选参数loadFactor通过指定用来计算分配给指定数量元素的空间数量的表的密度,进一步定制表的初始容量。 * 另外,为了和本类的之前版本兼容,构造函数可以指定可选项concurrencyLevel,用作内部尺寸的额外提示。 * 注意,对很多key使用同一个哈希码对任何哈希表来说都会降低性能。 * 为了改善哈希冲突,当key实现了Comparable,此类会使用key的比较顺序来打破僵局。 * *

A {@link Set} projection of a ConcurrentHashMap may be created * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed * (using {@link #keySet(Object)} when only keys are of interest, and the * mapped values are (perhaps transiently) not used or all take the * same mapping value. * 当只关注ConcurrentHashMap中的key,没有用到映射的值(可能是瞬时的)或者全部映射到同一个值, * 则可以使用newKeySet()、newKeySet(int)、keySet(Object)生成一个key的Set。 * *

A ConcurrentHashMap can be used as scalable frequency map (a * form of histogram or multiset) by using {@link * java.util.concurrent.atomic.LongAdder} values and initializing via * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count * to a {@code ConcurrentHashMap freqs}, you can use * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();} * ConcurrentHashMap通过使用LongAdder并且通过computeIfAbsent初始化可以作为一个可缩放频率的图(直方图或者多重集的形式)。 * 举个栗子,可以使用freqs.computeIfAbsent(k->new LongAdder()).increment();向ConcurrentHashMap freqs添加一个计数。 * *

This class and its views and iterators implement all of the * optional methods of the {@link Map} and {@link Iterator} * interfaces. * 本类及其视图和迭代器实现了Map接口和Iterator接口的所有可选方法。 * *

Like {@link Hashtable} but unlike {@link HashMap}, this class * does not allow {@code null} to be used as a key or value. * 本类不允许null作为key或者value,和HashTable而不是HashMap一样。 * *

ConcurrentHashMaps support a set of sequential and parallel bulk * operations that, unlike most {@link 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 {@link java.util.Map.Entry} * objects do not support method {@code setValue}. * 和大多数Stream方法不同,ConcurrentHashMap支持一系列顺序和并行批量操作,并且是安全合理的,即使有其他线程并发更新也可以使用。例如,计算一个共享登记表的值的摘要快照。 * 一共有3种操作,每种有4种形式,接受函数的参数和/或返回值为Keys,Values,Entries和(Key,Value)。 * 因为ConcurrentHashMap的元素没有以任何特定的方式排序,并且可能在不同的并行序列中以不同的顺序处理, * 所以所提供的函数的正确性不能依赖于任何排序或者任何在计算中可能瞬时改变的objects或values。并且除了forEach操作,都应该是完全无副作用的。 * Entry对象上的批量操作不支持setValue方法。 * *

    *
  • forEach: Perform a given action on each element. * A variant form applies a given transformation on each element * before performing the action.
  • * forEach:在每个元素上执行指定的操作。变体形式在执行操作前对每个元素应用给定的变换。 * *
  • search: Return the first available non-null result of * applying a given function on each element; skipping further * search when a result is found.
  • * search:将一个给定函数应用到每一个元素,返回第一个非空结果,找到结果后不再继续往后执行。 * *
  • 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: * reduce:累积每个元素。 提供的约简函数不能依赖于排序(更正式地说,它应该是关联和交换)。 有五种变体: * *
      * *
    • Plain reductions. (There is not a form of this method for * (key, value) function arguments since there is no corresponding * return type.)
    • * Plain reductions.(朴素规约?)(此方法没有(key,value)参数的形式,因为没有相应的返回类型) * *
    • Mapped reductions that accumulate the results of a given * function applied to each element.
    • * Mapped reductions(映射规约?)累计给定方法在每个元素上的返回结果。 * *
    • Reductions to scalar doubles, longs, and ints, using a * given basis value.
    • * Reductions()使用给定的基准值来度量doubles,longs和ints * *
    *
  • *
* *

These bulk operations accept a {@code parallelismThreshold} * argument. Methods proceed sequentially if the current map size is * estimated to be less than the given threshold. Using a value of * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value * of {@code 1} results in maximal parallelism by partitioning into * enough subtasks to fully utilize the {@link * 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. * 这些批量操作接受parallelismThreshold参数。如果当前map的预估大小小于给定阈值,方法顺序处理。 * 使用Long.MAX_VALUE阻止所有的并发性。 * 使用1来划分成足够多的子任务完全利用ForkJoinPool#commonPool()的并行计算,从而最大化并发性。 * 通常,你会从这些极值中选一个作为初始值,然后衡量使用中开销和吞吐量之间的性能。 * * *

The concurrency properties of bulk operations follow * from those of ConcurrentHashMap: Any non-null result returned * from {@code 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. * 批量操作的并发属性来自ConcurrentHashMap:get(key)及其相关访问方法返回的非空结果与其插入或更新操作存在happens-before关系。 * 任何批量操作的结果都反映了这些单个元素关系的组合(但是关于整个map不一定是原子性的,除非能够知道map是不变的)。 * 相反的,因为key和value一定不是null,所以null可以作为缺少元素的可靠标志。 * 为了保持该属性,null作为所有非标量规约操作的隐含基础。 * 对于double,long和int版本,当基础与其他值结合时,应返回其他值(更正式的说,应该是规约的标识元素)。 * 大多数常规规约都有这些属性,例如,计算基数为0的和或者基数为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. * 作为参数的搜索和转换函数应该同样返回null来表示元素的缺失(在这种情况下,结果不应被使用)。 * 在mapped reductions情况下,这也让转换能够当做过滤器,如果元素不需要组合,则返回null(或者在原始特殊化的情况下,返回标识基数)。 * 在搜索或缩减操作之前,你可以在"null表示元素不存在"的规则下,创建自己的复合转换和过滤方法。 * *

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 {@code new * AbstractMap.SimpleEntry(k,v)}. * 接收和/或返回Entry参数的方法维持key-value的关联。例如在查找最大value的key时,这可能是有用的。 * 注意,可以使用new AbstractMap.SimpleEntry(k,v)方法提供简单的Entry参数。 * *

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. * 通常并行比串行速度更快,但并不保证总是这样。 * 如果并行计算的潜在工作比计算本身更加耗时,那么在较小map上的简单并行操作可能比串行更慢。 * 同样的,如果所有的处理器处理不相关的任务,并行化可能不会有太多的实际并行性。 * *

All arguments to all task methods must be non-null. * 所有任务方法的所有参数都必须是非空的。 * *

This class is a member of the * * Java Collections Framework. **/

你可能感兴趣的:(源码阅读 - ConcurrentHashMap类注释)