Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see what objects have been garbage collected in Java?

Please, is there any way how to get history of objects (their variable or at least class names) that have been garbage collected in Java?

Just adding these params (to Oracle JVM)

-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps

doesn't provide anything else memory in bytes. It's very limited help to me. Thanks for all responses.

Note: Workaround with add finilize() method is not unfortunatelly an option for me (I don't have an access to it).

like image 840
Matt Avatar asked Sep 21 '11 10:09

Matt


People also ask

Which objects are garbage collected in Java?

Java Garbage collector tracks the live object and objects which are no more need are marked for garbage collection. It relieves developers to think of memory allocation/deallocation issues. When an object created in Java program is no longer reachable or used it is eligible for garbage collection.

How does Java garbage collector know which objects to free?

The garbage collector uses a traversal of the object graph to find the objects that are reachable. Objects that are not reached in this traversal are deemed garbage, even if they are part of a cycle of references.

How does Java know when to garbage collect?

As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.

Where is garbage collection in Java?

The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification. Although there are many JVMs, Oracle's HotSpot is by far the most common.


2 Answers

You can use the finalize method from Object. This method is called when the object is about to be GCed. From here, you can log the information you need.

like image 151
solendil Avatar answered Oct 03 '22 23:10

solendil


Disclaimer: My company develops the tool that I recommend in this answer.

In JProfiler you can go to the "Recorded objects" view in the memory section and switch the liveness mode to garbage collected objects (View->Change Liveness Mode->Garbage Collected Objects). You will then see a statistics of objects that have been GCed.

enter image description here

like image 42
Ingo Kegel Avatar answered Oct 04 '22 00:10

Ingo Kegel