Thursday, May 24, 2007

Garbage collection in Java

I am starting a series of posts on the Java garbage collector and various garbage collection algorithms. Over the 10 days or so, we will examine the Java garbage collector and garbage collection algorithms. Let's begin with a brief introduction.

An executing program occupies memory. Memory is taken as new objects are created. This memory should be returned when these objects are no longer needed. If it is not, then the computer will soon run out of resources, forcing the program to a halt. In C++ we have to explicitly return an object's memory back to the system when the object is destroyed. This is also the source for many bugs in C++. Buggy code that does not return memory can very soon exhaust system resources. To eliminate such errors, and make your program more robust, Java has adopted the philosophy of automatic memory reclamation. The JVM determines when an object is no longer needed (Eg: after the variable goes out of scope), and automatically reclaims memory occupied by that object. Objects no longer needed are known as 'garbage', because; well that is what we call things we no longer need, right? Hence reclamation of un-needed heap (Java objects are always created on the heap) memory is known as garbage collection in Java.

The JVM runs the garbage collector as a background thread, which constantly monitors the heap. The exact mechanism of reclaiming memory is JVM specific. The Java Language Specification (JLS) does not mandate any particular mechanism for garbage collection, hence it is implemented by the JVM creator.

There are several well known garbage collection algorithms that are implemented by modern JVM's. Each has pros and cons in terms of memory usage and performance. Some of these algorithms are:

  • Reference counting algorithms

  • Tracing algorithms

  • Compacting algorithms

  • Copying algorithms

  • Generational algorithms

  • Adaptive algorithms

In the next post we will discuss "Reference counting algorithms"

Discuss this post in the learning forum.

Commercial Links

No comments: