DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Java: Immortal Objects and Object Resurrection

Java: Immortal Objects and Object Resurrection

Learn how to make immortal Java objects by resurrecting objects that are about to be removed by Java's Garbage Collector. By using object resurrection, you can make your objects live as long as you want, without changing the applications that are using your objects.

Per-Åke Minborg user avatar by
Per-Åke Minborg
·
Apr. 05, 16 · Java Zone · Tutorial
Like (14)
Save
Tweet
17.96K Views

Join the DZone community and get the full member experience.

Join For Free

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

Object (computer science) Java (programming language)

Published at DZone with permission of Per-Åke Minborg, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Handling Sensitive Data: A Primer
  • A Guide to Events in Vue
  • ERP Integration Guide | Common Scenarios, Challenges, and Methods
  • Top 10 Criteria to Select the Best Angular Development Company

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo