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.
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
import java.io.*;
import java.util.*;
public class GFG {
private int num;
public GFG( int num)
{
this .num = num;
}
static final ArrayList<GFG> ar = new ArrayList<GFG>();
protected void finalize() throws Throwable
{
System.out.println( "Resurrect " + num);
ar.add( this );
}
public String toString()
{
return "Element{"
+ "num=" + num + '}' ;
}
public static void main(String[] args)
throws InterruptedException
{
for ( int i = 0 ; i < 3 ; i++)
ar.add( new GFG(i));
for ( int j = 0 ; j < 5 ; j++) {
System.out.println( "Elements : " + ar);
ar.clear();
System.gc();
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...