Island of Isolation in Java

Course Curriculum

Island of Isolation in Java

Island of Isolation in Java

In java, object destruction is taken care by the Garbage Collector module and the objects which do not have any references to them are eligible for garbage collection. Garbage Collector is capable to identify this type of objects.

Island of Isolation:

Object 1 references Object 2 and Object 2 references Object 1. Neither Object 1 nor Object 2 is referenced by any other object. That’s an island of isolation.
Basically, an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application. Strictly speaking, even a single unreferenced object is an island of isolation too.
Example:

public class Test
{
Test i;
public static void main(String[] args)
{
Test tmp1 = new Test();
Test tmp2 = new Test();

// Object of tmp1 gets a copy of tmp2
tmp1.i = tmp2;

// Object of tmp2 gets a copy of tmp1
tmp2.i = tmp1;

// Till now no object eligible
// for garbage collection
tmp1 = null;

//now two objects are eligible for
// garbage collection
tmp2 = null;

// calling garbage collector
System.gc();

}

@Override
protected void finalize() throws Throwable
{
System.out.println("Finalize method called");
}
}
Output:

Finalize method called
Finalize method called

Explanation :
Before destructing an object, Garbage Collector calls finalize method at most one time on that object.
The reason finalize method called two times in above example because two objects are eligible for garbage collection.This is because we don’t have any external references to tmp1 and tmp2 objects after executing tmp2=null.
All we have is only internal references(which is in instance variable i of class Test) to them of each other. There is no way we can call instance variable of both objects. So, none of the objects can be called again.

Till tmp2.i = tmp1 : Both the objects have external references tmp1 and tmp2.
Untitled_1

tmp1 = null : Both the objects can be reached via tmp2.i and tmp2 respectively.
Untitled_1

tmp2 = null: No way to reach any of the objects.
Untitled_1

Now, both the objects are eligible for garbage collection as there is no way we can call them. This is popularly known as Island of Isolation.

(Next Lesson) How to start learning Java