Island of Isolation in Java with example

The garbage collector is one of the significant natives in the Java world. It searches and removes all unused objects from the memory. With that way more space available in memory to store more new objects. If an object holds no references, then it is considered as qualifiable for Garbage Collection.

An island of isolation describes one or more object that references each other or even a single unreferenced object but has no references to any other active parts of an application.

The Island of Isolation in Java

Because the objects have no external reference and only isolated to hold an internal reference, the term Island of Isolation arises.

Let’s understand the Island of Isolation with some easy code example in Java,

class Employee{
  Employee e;    //instance variable

  public static void main(){
    Employee obj1 = new Employee();
    Employee obj2 = new Employee();

    obj1.e = obj2;    //object obj1 gets a copy of object obj2
    obj2.e = obj1;    //object obj2 gets a copy of object obj1

    //No object qualified for garbage collection till now
    obj1 = null;
    obj2 = null; 

    //Now 2 objects are eligible for garbage collection 
    System.gc();    //Calling garbage collector
  }

  @Override
  protected void finalize() throws Throwable{
    System.out.println("Finalize Method Called");
  }
}

Output :

Finalize Method Called
Finalize Method Called

Explanation:

Before the destruction of any object that has no more external reference, the finalize method is called to perform some clean-up activities.
Because in the given code, there are two objects having no external reference, so finalize method called two times.

After executing obj2=null, there is no external reference to obj1 and obj2 objects.
There is only internal reference which is in an instance variable e and can not call the instance variable of both objects.

 

Till obj2.e = obj1: obj1 keeps obj2 inner reference and obj2 keeps obj1 inner reference.

Island of Isolation 1

After obj1 = null: obj2 is as yet referenced by the obj2 and the obj2 still has a reference to the obj1.

Island of Isolation 2

After obj2 = null: Both objects obj1 and obj2 have no more external reference.

Island of isolation 3

Now there is no external reference between objects obj1 and obj2, so they are qualified for garbage collection. And hence the term Island of Isolation arises.

 

You should also go through,

Leave a Reply

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