Over a million developers have joined DZone.

Faster Repeated Access to Java Class Names Coming to Java?

DZone's Guide to

Faster Repeated Access to Java Class Names Coming to Java?

As we continue the game of which fancy features are coming to Java next, we examine a proposal to cache class names to boost performance.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Claes Redestad has posted the message "RRF: 8187123: (reflect) Class#getCanonicalName and Class#getSimpleName is a part of performance issue" on the core-libs-dev mailing list in which he requests a review of a proposed change "to enable caching of getCanonicalName and getSimpleName, repeated calls of which has been reported to be a performance bottleneck." He adds that "the caching improves performance of these methods by up to 20x."

An obvious solution to the performance issue might have been to add the name of the class as a field to the Class class definition, but Redestad points out in the associated bug JDK-8187123 that "we should avoid adding more fields to java.lang.Class." Instead, this bug was addressed by the idea to "piggy back off other reflection information that is cached in ReflectionData."

ReflectionData is a nested (private static) class defined within the Class class. The Class class's reference to ReflectionData is defined as:

private volatile transient SoftReference<ReflectionData<T>> reflectionData;

The Class instance holds a soft reference (java.lang.ref.SoftReference) to the instance of nested class ReflectionData. The class-level Javadoc for SoftReference states that a soft reference is "cleared at the discretion of the garbage collector in response to memory demand" and that a soft reference is "most often used to implement memory-sensitive caches." This seems like a nice solution to balance performance and memory concerns.

The mailing list message references a link to the proposed changes to Class.java. Reviewing those changes, one can quickly see how the proposed code changes add three new Strings to the attributes contained in an ReflectionData instance to represent canonical name, simple name, and type name. Of course, the three methods that provide access to those details [getCanonicalName(), getSimpleName(), and getTypeName()] are changed to use these values.

As of this writing, JDK-8187123 has not been associated with a particular Java release.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

java ,java performance ,caching ,class names

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}