Question

I want to implement a behavior on an object which is similar to a guaranteed finalize() in the Java language. I want some statements to be executed just before garbage collection happens. Please note that finally block is not useful here as finally runs just after the try block, which isn't my requirement. Basically I want to serialize the object just before it gets unloaded from JVM's heap. Please advise.

Was it helpful?

Solution

You can add a hook in the JVM on shutdown; see http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29

Together with the phantoms from @user949300 that seem workable. The hook however needs to store weak references to all objects. If you create a java Service interface for the hook, you can use it in object constructors. But ugly isn't it?

OTHER TIPS

There is no way to implement a finalize() method that will be executed no matter what because the JVM is not guaranteed to call it. For example, objects left on the heap when your program exits might never have their finalize() method called, depending on the current JVM.

It is generally not advised to use finalize() to free any resources except memory, much less to do anything else than freeing resources. If you want to serialize your objects, try choosing a different point in time.

There is a good article summarizing almost all you need to know about finalizers.

I have never used a Phantom Reference (sounds like one of the bad Star Wars movies) but it sounds like it might do the trick.

"Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top