JDK-8169425 : Values computed by a ClassValue should not strongly reference the ClassValue
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 9
  • Priority: P3
  • Status: Open
  • Resolution: Unresolved
  • Submitted: 2016-11-08
  • Updated: 2025-06-09
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
Other
tbdUnresolved
Related Reports
Relates :  
Relates :  
Description
A computed value produced by a ClassValue instance should not strongly refer to that instance, for example:

class Holder {
  Object o;
  Holder(Object o) { this.o = o; }
}

class MyClassValue extends ClassValue<Holder> {
  Holder computerValue(Class<?> type) {
    return new Holder(this);    
  } 
} 

In the current JDK implementation this will prevent classes from being garbage collected and therefore cause a memory link.

Rather than changing the implementation of ClassValue to support such an edge case it is preferred to update the documentation of ClassValue.computeValue warning against such behaviour.
Comments
It is unfortunate that this comment never landed. I could have used it in debugging an issue that just came up: https://github.com/oracle/graal/issues/3260 I think we can rewrite our uses of ClassValue to not use back references, but it came at a big surprise to me.
08-04-2021

Proposed documentation changes: --- a/src/java.base/share/classes/java/lang/ClassValue.java Tue Nov 08 12:36:21 2016 -0800 +++ b/src/java.base/share/classes/java/lang/ClassValue.java Tue Nov 08 15:25:04 2016 -0800 @@ -62,6 +62,13 @@ * If this method throws an exception, the corresponding call to {@code get} * will terminate abnormally with that exception, and no class value will be recorded. * + * @apiNote + * Care should be taken to ensure that this {@code ClassValue} is not + * <a href="../ref/package-summary.html#reachability"><em>strongly reachable</em></a> + * from the computed value. Doing so may prevent classes and their loaders + * from being garbage collected which in turn may induce out of memory + * errors. + * * @param type the type whose class value must be computed * @return the newly computed value associated with this {@code ClassValue}, for the given class or interface * @see #get
05-05-2017