Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Object Resurrection in Java

  • Last Updated : 18 Aug, 2021

In object-oriented programming languages with garbage collection, object resurrection is when an object comes back to life during the process of object destruction, as a side effect of a finalizer being executed.

Object resurrection causes a number of problems, particularly that the possibility of object resurrection even if it does not occur makes garbage collection significantly more complicated and slower, and is a major reason that finalizers are discouraged. Languages deal with object resurrection in various ways, as solutions to these problems. In rare circumstances, object resurrection is used to implement certain design patterns, notably an object pool, while in other circumstances resurrection is an undesired bug caused by an error in finalizers, and in general, resurrection is discouraged.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

An object becomes garbage when it is no longer reachable from the program and maybe collected (destroyed and reallocated). Then, during object destruction, before the garbage collector deallocates the object, the finalize method may be run, which may, in turn, make that the garbage object reachable again by creating references to it.

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. In the last half output is illustrated with the help of a video illustration of how the output is retained on the screen for the clear’ sake of understanding.



Example:

Java




// Java Program to illustrate Object Resurrection
 
// Importing all utility classes from java.util package
// Importing all input output classes from java.io package
import java.io.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Member variable of this class
    private int num;
 
    // Constructor of the class
    public GFG(int num)
    {
 
        // This keyword refers to current instance
        this.num = num;
    }
 
    // Creating an ArrayList class object
    // Declaring object of class type
    static final ArrayList<GFG> ar = new ArrayList<GFG>();
 
    // Method 1 (protected)
    protected void finalize() throws Throwable
    {
 
        System.out.println("Resurrect " + num);
 
        // Adding the current instance to object
        // using this operator
        ar.add(this);
    }
 
    // Method 2
    // Standard way to convert to string type
    public String toString()
    {
 
        return "Element{"
            + "num=" + num + '}';
    }
 
    // Method 3
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
 
        // Iterating using nested for loops
        for (int i = 0; i < 3; i++)
            ar.add(new GFG(i));
        for (int j = 0; j < 5; j++) {
 
            // print the element in the object
            System.out.println("Elements : " + ar);
 
            // Clearing off elements using clear() method
            ar.clear();
 
            // Garbage collector
            System.gc();
 
            // Making the thread to sleep for a 1/10 sec
            // using the sleep() method
            Thread.sleep(500);
        }
    }
}

Output : 

Elements : [Element{num=0}, Element{num=1}, Element{num=2}]                                                                            
Resurrect 2                                                                                                                            
Resurrect 1                                                                                                                            
Resurrect 0                                                                                                                            
Elements : [Element{num=2}, Element{num=1}, Element{num=0}]                                                                            
Elements : []
Elements : []
Elements : []

Output Explanation:

The elements are added once to the collection and resurrected once by the finalize method. When they are collected a second time, they have been flagged as finalized and not queued again. It is demonstrated with the help of video output.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!