Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of Holder class in HashMap?

I have found that in HashMap we have an inner class Holder with the following description:

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

How and when we have to use that class? what is the utility of it. Please explain.

like image 1000
Ankush soni Avatar asked Apr 28 '15 11:04

Ankush soni


1 Answers

This is related to the improvements of Java 7u6, and has been removed in Java 8.


Relevant documentation:

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.

...

and

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.


Now, to answer your question:

How and when we have to use that class?

What makes you think you should use it? It's a private class without any public docs, so you don't have to care about it. It's an implementation detail of Oracle's HashMap and you can't use it directly. The only way you could indirectly use it is via the jdk.map.althashing.threshold system property.

And why did Oracle's engineers use such a holder? Because of classloading order. It's pretty difficult for the VM to load all the classes when they have lots of dependencies on each other, it could potentially get stuck. Therefore, the developers of all internal classes much make sure they're not using methods/properties of classes that might not be loaded yet / could cause load order problems.

This is one such helper, it initializes a value only after all other classes are loaded and the VM is fully booted. The value in the holder will get initialized only once the class gets accessed for the first time, and this access is shielded with a sun.misc.VM.isBooted() call.

like image 85
Petr Janeček Avatar answered Sep 24 '22 03:09

Petr Janeček