Witscale Test Center

6.8 What garbage collection does not guarantee


6.8 What garbage collection does not guarantee

You may think that since Java does most of the memory management work; there won’t be any memory leaks. This is not true as you can still have memory leaks despite excellent work of garbage-collection. A memory leak occurs when the allocated memory is not freed although it is never used again. This can happen due to poor programming. For instance, assume that you place object references in an array (or in a collection) and work on the objects pointed to by the references. After you have finished processing, you forget to remove them from the array. Now these objects will stay on the heap as long as the array object lives. They won't be collected by the garbage collection because there is still a reference to them in the array. Therefore they are reachable. But they are of no use to you as you are done working on them. Over time, the number of objects in the array may keep growing. This is a potential memory leak and can cause problem if the array object is not garbage collected for a long time. Therefore, the key point to remember is that garbage collection cannot guarantee against memory leak.

   Another thing that garbage collection won’t guarantee is that the application won’t run out of memory. You java application can run out of memory if you create too many reachable objects. Garbage collection can reclaim memory of only unreachable objects. Therefore, following code may throw a OutOfMemoryError as it creates a lot of reachable objects.

 

public static void main(String[] args) {

  Car[] carArray = new Car[10000000];

  for (int i = 0; i < carArray.length; i++) {

    carArray[i] = new Car();

     }

}

 

Since the all the Car objects are reachable ( till the main method is running), the garbage collector may not collect them and your program may run out of memory. So garbage collection cannot guarantee that you will always have enough memory. All it can guarantee is to manage the available memory as efficiently as possible.