1.

Is it possible to «resurrect» an object that has become eligible for garbage collection in Java?

Answer»

The Garbage Collector (GC) must CALL the FINALIZE method on an object when it becomes garbage COLLECTION eligible. Because the finalize method can only be used once, the GC marks the object as finalized and sets it aside until the next cycle.

You can technically "resurrect" an object in the finalize method by assigning it to a static field, for example. The object would revive and become ineligible for garbage collection, preventing the GC from collecting it in the next cycle.

The object, on the other hand, would be marked as finalized, thus the finalize method would not be invoked when it became eligible again. In essence, you can only use this "resurrection" method only once.

Example:

// Java Program to illustrate Object Resurrectionimport java.io.*;import java.util.*;public class InterviewBit { private int num; // Constructor public InterviewBit(int num) { // assigning the parameter value to the member variable this.num = num; } // Creating an ArrayList of class object static final ArrayList<InterviewBit> ar = new ArrayList<InterviewBit>(); protected void finalize() throws Throwable { System.out.println("Resurrect " + num); // By using the this operator, adding the current instance to object ar.add(this); } public String toString() { return "Element(" + "number = " + num + ')'; } public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 3; i++) ar.add(new InterviewBit(i)); for (int j = 0; j < 5; j++) { // printing the element in the object System.out.println("The Elements are : " + ar); // Clearing off elements ar.clear(); // Calling the garbage collector function System.gc(); // Making the THREAD to sleep for 500 ms Thread.sleep(500); } }}

Output:

The Elements are : [Element(number = 0), Element(number = 1), Element(number = 2)]Resurrect 2Resurrect 1Resurrect 0The Elements are : [Element(number = 2), Element(number = 1), Element(number = 0)]The Elements are : []The Elements are : []The Elements are : []

Explanation:

The finalize method adds the items to the collection once and then resurrects them. They have been marked as finalized and will not be queued again when they are collected a second time.



Discussion

No Comment Found