Minborg

Minborg
Minborg

Monday, March 7, 2016

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.

1 comment:

  1. So, at the end, when use finalize!? Nowadays there's a real usecase?...It's however enough risky: is it better to use PhantomReference and ReferenceQueue? There's also the problem of implicit creation of Finalizer objects, based on JVM that you use, right?...

    ReplyDelete

Note: Only a member of this blog may post a comment.