views:

578

answers:

3

I would like to get a reference to all objects in the Java heap, even if I don't immediately have a reference to those objects in my active thread. I don't need non-referenced objects (those "queued" for garbage collection), but would like to get anything that's still in use.

The goal is to serialize and store all the objects to implement a poor-man's persistence of execution state. I realize that the rabbit hole goes deep when it comes to different types of transient state, but simply persisting objects & loaded class definitions would be useful to me.

Is there a way to access the heap in order to make this happen? Am I overlooking a more straightfoward approach?

+1  A: 
Robert Munteanu
I'm assuming he wanted to accomplish this via code.
MattC
Still, that's pretty cool. I'll have to check it out.
MattC
Greg Harman
+2  A: 

I'd look into the the instrument package. Instrument the classes you are interested in so the ctor registers the created instance. You might be able to do this via AspectJ should you not want to use the java.lang.instrument or if the objects are created via something you can control (an IoC container or factories) then you can do something a good chunk less magical.

mlk
I like this approach, as it gives me a good hook to work with the objects. Thanks.
Greg Harman
+1  A: 

If you want to take a heap dump programmatically, you'll not find suitable APIs in the java.* or javax.* namespace. However, the Sun runtime comes with the HotSpotDiagnosticMXBean which will enable you to take a heap dump by writing the contents of the heap on to a specified file in disk.

Vineet Reynolds