Core Java

Java: Immortal Objects and Object Resurrection

What is Object Resurrection?

A Java object is eligible for Garbage Collection when no other object references the object. When the JVM:s Garbage Collector eventually is about to remove an unused object, the object’s finalize() method is invoked. But, if we re-create a reference to the object again in the object’s own finalize() method, the object can be resurrected. In such cases, the JVM will detect that the object is again referenced and will refrain from removing it. Metaphorically, the object has been resurrected from death…

public class Immortal {

    private static final Set<Immortal> immortals = new HashSet<>();

    @Override
    protected void finalize() throws Throwable {
        System.out.println(Immortal.class.getSimpleName() + "::finalize for " + this);
        immortals.add(this); // Resurrect the object by creating a new reference 
    }

}

The resurrection property can be tested the following way:

public class NewMain {

    public static void main(String[] args) {
        new Immortal();
        System.gc();
        sleep(1_000);
        System.gc();
        prompt("Press any key...");
    }

    private static void prompt(String msg) {
        try {
            System.out.println(msg);
            System.in.read();
        } catch (IOException io) {
        }
    }

    private static void sleep(long duration) {
        try {
            Thread.sleep(duration);
        } catch (InterruptedException ie) {
        }
    }

}

Which will give the following output:

Immortal::finalize for com.blogspot.minborgsjavapot.resurected_object.Immortal@635cb856
Press any key...

By inspecting the Java heap, we can also see that the object is still there despite its finalizer was called:

pemi$ jps
21735 NewMain
21736 Jps

pemi$ jmap -histo 21735 | grep Immortal
 164:             1             16  com.blogspot.minborgsjavapot.resurected_object.Immortal

 

How Many Times is the Finalizer Invoked?

If a resurrected object is later de-referenced, it is again eligible for Garbage Collection. However, this time the
finalize() method will not be invoked again since Java only invokes the finalizer at most one time. As we may recall, there is no guarantee that the finalizer is ever invoked. For example, if the program terminates for any reason, the objects in the JVM are simply abandoned and their finalizers will not be invoked at all as can be seen in this example:

public class NewMain2 {

    public static void main(String[] args) {
        new Immortal();
    }

}

When we run the above code snippet, we observe that the Immortal::finalizer is never called.

Is Object Resurrection Good?

As always when using the finalize() method, we must be very cautious. The general recommendation for us Java developers is to not use finalize() at all. Furthermore, one could argue that resurrecting an object is the same as intentionally creating a memory leak.

However, there are some interesting applications for object resurrection. Perhaps we want to do some post-mortal analysis of our objects without changing the actual application that are using the objects. By using object resurrection, we could save those objects and analyze their internal state later, independently of the applications that are using them.

Per Minborg

I am a guy living in Palo Alto, California, but I am originally from Sweden. I am working as CTO on Speedment with Java and database application acceleration. Check it out on www.speedment.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Simon
Simon
8 years ago

Using finalize has been considered very poor practice for many years now, not least because it really messes up the garbage collector’s ability to work efficiently. I believe you’ll find that the use case you suggest (post mortem debugging, which is indeed an interesting one) can in fact be achieved with a bit of effort using the references API. If you use this approach instead, you’ll immediately gain two substantial benefits: 1) You need not mess with the garbage collector in the same evil way 2) Your debugging behavior, with its inevitable system load, can be turned off when you… Read more »

Back to top button