Island of Isolation in Java with Example

The concept of garbage collection and island of isolation go hand-in-hand in Java. To be precise, the island of isolation is a subpart of garbage collection in Java.

This article will give you insights into both these concepts in a clear manner. It would help if visit the “Garbage Collection in Java” article at FirstCode before getting to know about the Island of isolation. Let us now get into our main topic.

Island of isolation in Java:

The Garbage Collector module does the destruction of objects. The objects that do not have any sort of references to them are eligible for garbage gathering. We use a Java garbage collector to identify such objects.

In a situation when Object 1 references Object 2 and Object 2 references Object 1, but neither Object 1 nor Object 2 is referenced by another object, this is an island of confinement.

Now, collecting all the items that reference each other but are not referenced by another dynamic object in the application is termed an island of isolation.

Sample program to implement the Island of Isolation in Java:

public class FirstCode     
{     
FirstCode i;     
public staticvoid main(String[] args)      
{     
Test t1 = new Test();     
Test t2 = new Test();     
t1.i = t2;    //object of t1 gets a copy of t2     
t2.i = t1;    //object of t2 gets a copy of t1     
// no objects is eligible for garbage collection     
t1 = null;        
t2 = null;  // two objects are eligible for garbage collection     
System.gc();     
}     
@Override     
protected void finalize() throws Throwable     
{     
System.out.println("Calling the finalize method");     
}     
}     

Output:
Calling the finalize method
Calling the finalize method

Program explanation:

Before object destruction, the garbage collector invoke the finalize methods for one last time on the instance. In the given example, we call the finalize method twice as the count of objects qualifiable for garbage collection is two.

This is due to absence of external forces to t1 and t2 after executing t2 = null. Only internal references to these values are present. In addition to it, we can call no other objects as there is no likelihood to call an instance variable of both the objects.

program explanation

Till t2.i = t1: Both the objects have external references t1 and t2.

program explanations

t1 = null: Both the objects can be reached via t2.i and t2 respectively.

program-explained

Here, both the objects are eligible for garbage collection as there is no way to call them. This is the Island of isolation.

Conclusion:

Now, you might be clear about the Island of Isolation in Java and how to use it in Garbage Collection. You also got to learn how to make an object eligible for garbage collection. Try the sample program to find the working of this concept.

Leave a Reply

Your email address will not be published. Required fields are marked *