HashMap中的Holderclass有什么用?

What is the use of Holder class in HashMap?

我发现在 HashMap 中我们有一个内部 class Holder 具有以下描述:

/**
 * holds values which can't be initialized until after VM is booted.
 */

我们必须如何以及何时使用它 class?它有什么用处。请解释。

这与 Java 7u6 的改进有关,已在 Java 8 中删除。


相关文档:

Collections Framework Enhancements in Java SE 7

The alternative hash function improves the performance of these map implementations when a large number of key hash collisions are encountered.

For Java SE 7u6, this alternative hash function is implemented as follows:

The alternative hash function is only applied to maps with a capacity larger than a specified threshold size. By default, the threshold is -1. This value disables the alternative hash function. To enable the alternative hash function, set the jdk.map.althashing.threshold system property to a different value. The recommended value is 512. Setting this system property to 512 causes all maps with a capacity larger than 512 entries to use the alternative hash function. You can set this system property to 0, which causes all maps to use the alternative hash function.

...

Collections Framework Enhancements in Java SE 8

The alternative String hash function added in 7u6 has been removed from JDK 8, along with the jdk.map.althashing.threshold system property. Instead, hash bins containing a large number of colliding keys improve performance by storing their entries in a balanced tree instead of a linked list.


现在,回答你的问题:

How and when we have to use that class?

是什么让您认为应该使用它?它是私有的 class without any public docs,因此您不必关心它。它是 Oracle 的 HashMap 的实现细节,您不能直接使用它。您可以间接使用它的唯一方法是通过 jdk.map.althashing.threshold 系统 属性.

为什么 Oracle 的工程师要使用这样的支架?由于 class 加载顺序。当 classes 彼此有很多依赖关系时,VM 很难加载所有这些,它可能会卡住。因此,所有内部 classes 的开发人员都非常确保他们没有使用可能尚未加载/可能导致加载顺序问题的 classes 中的 methods/properties。

这就是一个这样的助手,只有在加载所有其他 classes 并且 VM 完全启动后,它才会初始化一个值。 holder 中的值只有在 class 第一次被访问时才会被初始化,并且此访问被 sun.misc.VM.isBooted() 调用屏蔽。