Matt Warrick
Matt Warrick

Reputation: 1488

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).

Upvotes: 8

Views: 6506

Answers (5)

Matthias Ronge
Matthias Ronge

Reputation: 10112

Weak references or phantom references seem to be useful to log when the object actually gets removed. In this article the technology is explained.

Upvotes: 0

BrownFurSeal
BrownFurSeal

Reputation: 515

There is a nice built-in tool in JDK for observing jvm in runtime. It is jvisualvm. There is a a good reference with screenshots: http://visualvm.java.net/description.html

Here is one of them : enter image description here

Hope that helps.

Upvotes: -2

Ingo Kegel
Ingo Kegel

Reputation: 47975

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

Upvotes: 4

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Are you searching for a memory leak?

If you implement finalize() method (available in every Object) it will get called just before the object is being garbage collected - and you can run any code inside it.

If you are looking for a systematic solution (or you don't have access to classes you want to monitor), I am not aware of any JVM option that allows that. However you can log classes being loaded and unloaded (GCed), but this is not what you are asking.

Upvotes: 0

solendil
solendil

Reputation: 8468

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.

Upvotes: 5

Related Questions