How to use Garbage Collector
The Garbage Collector has evolved so much that for the Java 1.6 you know for sure:
- it uses different methods to manage references and the corresponding Heap addresses; the most trivial method is that is uses a table to count how many references are used to reach a Heap memory zone; when the number of references gets to 0 then the memory zone is released;
- it is a complex and very efficient JVM routine that will not interfere with your Java process performance;
- it will not save any out of memory situation (OutOfMemoryException); remember that any live object (it is reachable by a live reference) it is not collected;
- you can request garbage collector to make a memory clean explicitly by invoking theSystem.gc( ) method;
- it is not recommended to interfere with the garbage collector by calling System.gc( ) method, because you have not any guarantees on how it will behave;
How to generate unreachable objects or memory leaks
In order to generate unreachable objects or memory leaks and to enjoy the benefits of having a Garbage Collector you must loose or remove all the references for that object.
1. The simplest way is to null a reference:
In this way the object becomes eligible for garbage collector because we don’t have any other reference used to reach the object.
2. Reassigning the reference we make the previous object unreachable:
In this way the first object becomes eligible for garbage collector because we don’t have any other reference used to reach the object.
3. Isolating a reference it is a more hidden scenario because at a first glance you may say that your object is still alive. If we consider the next class:
3. Isolating a reference it is a more hidden scenario because at a first glance you may say that your object is still alive. If we consider the next class:
you can see that every Student object contains an array reference as an instance variable. If we test the class like this
it is clear that the Student object is going to be collected by the GC. But, what is going to happen with the integers array inside the object. If we analyze the Heap, we can see that the array object is still reachable through the marks reference.
Posted in: