Search code examples
javagarbage-collectionjvmjvm-hotspotjvmti

Can I programmatically find out in which GC generation an instance lives?


This question is limited in scope to HotSpot generations. Is there any way to programmatically find out in which generation a particular instance lives. Data such as:

  • Young or old generation?
  • If young, which survivor space?
  • Inside TLAB? Which thread?

Any technique (ex., BTrace, JVMTI) works so long as I can do something like this:

Object x = new Object();
HotSpotGenerationInfo info = HotSpotGenerationUtil.getInfo(x);

Beggars can't be choosers but ideally I could also learn when the instance of interest was being moved from one generation to another at the moment it happens (i.e., event callback based -- not interested in the delay & overhead implicit in polling.)

Not interested in answers that just say "no" without justification :)


Solution

  • As far as I know, you can not directly query which memory pool an object currently lives in. However, objects are promoted to a different memory pool by a garbage collection run, and you can query the number of major/minor gc runs since VM start using JMX. If you additionally take note of these counters when the object is created, you can reconstruct whether there was a GC since and from that which pool the object lives in.