JDK-8206208 : Class::newInstance leaks the caller Class
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 10.0.1
  • Priority: P3
  • Status: Resolved
  • Resolution: Duplicate
  • Submitted: 2018-07-02
  • Updated: 2018-07-03
  • Resolved: 2018-07-03
Related Reports
Duplicate :  
Relates :  
Description
A DESCRIPTION OF THE PROBLEM :
I've originally reported this bug, but I'm sorry to say we've missed one case that is still leaking.

The case when java.lang.Class.newInstance() method is called, it's code is leaking the caller Class forever in its member `newInstanceCallerCache`

How to reproduce? Very easy, just call something like `java.lang.String.class.newInstance()` and it will cache the caller.
Adding that flow to your unit-tests ReflectionCallerCacheTest.java will show it up

The fix I think we should introduce is something like saving the caller under a WeakReference ?
Because the caller class will never be freed as long as the classloader and its users are in use, so the weakreference will stay as long as the class has some other path to GC.


This bug is even trickier since this leak isn't even visible thru EclipseMAT/HPROF dumps, because Class object instance don't have their fields dumped into the HPROF
(`HeapObjectDumper::do_object` is skipping Class objects, and thus their fields aren't available in MAT analysis, so the leak isn't visible there and was very hard to find)

I've tried to submit this bug few days ago, under 9055846, but didn't got any response yet

REGRESSION : Last worked in version 8u172

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Add to unit-tests of ReflectionCallerCacheTest.java step which calls code such as:
   java.lang.String.class.newInstance()

and then it will be leaked

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
not leak the caller class forever

CUSTOMER SUBMITTED WORKAROUND :
There's none, and it even much harder to find since Class objects don't expose their fields in HPROF heapdump, so its almost impossible to find those leaks.

FREQUENCY : always