Monday, April 30, 2018

Faster Repeated Access to Java Class Names Coming to Java?

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 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.

No comments: