The second way of regaining memory is through garbage collection. This is mainly used when references are used and was made popular by the language called Java. When you have a reference to memory you will always deal with it indirectly. As such you do not have the responsibility to de-allocate it. What the language does behind the scenes is keep track of these references. Consider the following code

  1. myReference() {
  2. Collection col = new ArrayList();
  3. }

Line 2 has requested memory using the new command. Java, the language used here, has now returned a reference , col, in order to access the heap memory. The next line is the end of the function. We have not actually done anything with our reference. References obey the same rules as variables. As such we know that the reference col has dropped out of scope.

When memory is allocated garbage collectors will create a reference count for that memory. As we are assigning the reference to a variable we add one to the reference count. When the variable which holds the reference drops out of scope we reduce the reference count by one. When the reference count is zero this means that no part of the code can access the memory anymore. It is then marked for garbage collection. This means that the garbage collector, at some time in the future, will release the memory.

By keeping track of references the garbage collector will know when it can delete memory. As the process of garbage collection is actually quite time consuming it will not be done all the time. In fact it does not run very often at all. So when the reference count is set to zero there will be a undisclosed time delay before the memory is released. It is possible to ask the garbage collector to run through code. However not all languages will guarantee that this will happen. Java treats it as a hint and will not run it on demand.

It is possible to have multiple references to a chunk of memory. As such it is possible to write code which never releases a block of memory. This is normally through bad programming. If you are interested there are many interesting discussions on this topic on the web.