Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
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 }}