Back to homepage

Classes as Map keys in Java

Posted on February 12, 2017

By accident I came across this interesting class. I suggest you to read its source code, its very unusual. But I struggled to understand the purpose of this class. The reason for its existence is even more interesting.

If you need to store the relation between two objects you use a Map, right? But when the key instance is of class type it gets more complicated. Best explanation can be found here JDK-6389107.

My TLDR version of it:
When the key in a Map is Class instance, this class instance now cannot be garbage collected. No big deal you might add. But class holds reference to its class loader and this class loader holds references to all classes it has loaded. Now that might be a problem. It can also lead to locking the jar files containing the class files. There are some solutions but they all suck.

And here comes the ClassValue utility. It maps classes to some other representation. It does it lazily and caches the result. ClassValue is also thread safe. Thread safety is implemented in very unusual way. Read get method and remove method javadoc to grasp the idea. Reading the source code is not that easy though.

Be careful when using Classes as keys in your maps!

Some links:
O answer with some info abou Class value
Is using the Class instance as a Map key a best practice?