Reputation: 1095
This is mostly about the Oracle Java 8 JVM. Assume I don't have access to logs. Java is not running in verbose mode and stdin / stderr are not being logged.
Is there any place within the running JVM where it keeps the timestamp of the last GC event? Or anything else that might indicate when the last GC event took place?
I just want to know how long ago the last GC event happened. Bonus points for differentiating between different types of GC events.
Upvotes: 2
Views: 456
Reputation: 298599
When you are fine with a solution that works with Oracle’s Java 8 JVM and might work with others, you can use the GarbageCollectorMXBean
platform extension. I linked to the JDK 11 documentation, as this class is not included in JDK 8’s documentation, but this type is present and the following solution works.
final RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
long base = rt.getStartTime();
for(GarbageCollectorMXBean gc: ManagementFactory.getGarbageCollectorMXBeans()) {
if(gc instanceof com.sun.management.GarbageCollectorMXBean) {
com.sun.management.GcInfo info =
((com.sun.management.GarbageCollectorMXBean)gc).getLastGcInfo();
if(info != null) {
System.out.printf("%-15s%tF %2$tT.%2$tL (%6dms ago)%n",
gc.getName(), base + info.getStartTime(), rt.getUptime()-info.getStartTime());
}
}
}
When I prepended
System.gc();
System.out.println(System.getProperty("java.version"));
for a simple run, I got
1.8.0_131
PS Scavenge 2019-04-09 11:58:25.808 ( 50ms ago)
PS MarkSweep 2019-04-09 11:58:25.809 ( 74ms ago)
This information can also be queried remotely, see also Ways to Access MXBeans. It works if the JVM has the Management Agent already running or is reachable via the Attach API (usually implies running on the same computer), so the Management Agent can be started later on. These options are also what tools like VisualVM use.
Upvotes: 1