4

I am aware that you can use the -verbosegc to print information about the GC to the sysout but I don't want that. I want to intercept whenever GC triggers and print information about it to my custom logger, perhaps save last GC timestamp on a internal variable, etc.

Any hope here?

chrisapotek
  • 6,007
  • 14
  • 51
  • 85

6 Answers6

3

You can't hook the GC logging mechanism from within a Java program because when the GC thread(s) run the JVM is effectively stopped. Doing so would cause a deadlock so its a good thing we can't. Even using a custom launcher to try and hook via some handle reopen technique and calling up to Java would deadlock. Maybe if a reopen from within a custom launcher was possible (I don't know one way or the other) buffering the data and jumping from Java to native via JNI to retrieve the buffer might work.

Java42
  • 7,628
  • 1
  • 32
  • 50
2

As of Java7u4, you can get notifications from the GarbageCollectorMXBean. See http://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/GarbageCollectionNotificationInfo.html

There is a nice example here: http://www.fasterj.com/articles/gcnotifs.shtml

retrospectacus
  • 2,518
  • 1
  • 11
  • 18
2

I don't think it is possible to do this directly. AFAIK, this logging is performed at a very low level and is effectively outside of the reach of normal Java programs.

Instead, I think you'll have to configure the JVM to write the GC messages to a known file (using the JVM opts) and then use a file tailer to read the messages as they are written to the file.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

You can use the JVM param -Xloggc:[filename]

Daniel Pereira
  • 2,720
  • 2
  • 28
  • 40
1

You can redirect System.out and System.err to a log file. There's an example for java.util.logging here. Other packages can do the same thing AFAIK.

BillRobertson42
  • 12,602
  • 4
  • 40
  • 57
  • This is true, but I don't think it is relevant to GC logging. – Stephen C Mar 24 '12 at 17:13
  • I was thinking about that too. Its possible that that information is spit out at a lower level (e.g. in C code), and if that's true then it might not be possible to intercept it. Its worth a try though. – BillRobertson42 Mar 24 '12 at 18:58
0

You can add your interceptor code in 'finalze ()' method, but for that you have to override the finalize method for all your objects.

Note also that the finalize method is not necessarily called before the GC process.

glautrou
  • 3,140
  • 2
  • 29
  • 34
abk
  • 106
  • 1
  • 4