Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection notification?

I'd like to register a callback with the JVM so I know when garbage collection is happening. Is there any way to do this?

EDIT: I want to do this so I can log out when garbage collection happens in my application log, so I can see if it correlates to problems I'm seeing. Turning on -Xloggc is helpful, but it is a little tricky to integrate the times from the GC log (which use seconds since app start) into my main application log.

EDIT April 2012: As of Java7u4, you can get notifications from the GarbageCollectorMXBean (a nice example).

like image 867
Ted Graham Avatar asked Jan 13 '10 15:01

Ted Graham


People also ask

Does garbage collection happen automatically?

In Java, garbage collection happens automatically during the lifetime of a program. This eliminates the need to de-allocate memory and therefore avoids memory leaks. Java Garbage Collection is the process by which Java programs perform automatic memory management.

Can we enforce garbage collection?

Your best option is to call System. gc() which simply is a hint to the garbage collector that you want it to do a collection. There is no way to force and immediate collection though as the garbage collector is non-deterministic.

What triggers garbage collection?

When a JVM runs out of space in the storage heap and is unable to allocate any more objects (an allocation failure), a garbage collection is triggered. The Garbage Collector cleans up objects in the storage heap that are no longer being referenced by applications and frees some of the space.


1 Answers

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

like image 166
Ted Graham Avatar answered Sep 22 '22 23:09

Ted Graham