What are the pros and cons of Garbage Collector in Java?

The Java Runtime Environment (JRE) provides automatic memory management that is implemented at the programming language level. With Java, a programmer need not to worry about deallocating or freeing objects from the memory.

Heap is the area of memory where objects are stored. The heap implementation supports the relocation of objects in memory to reorganize memory and improve its efficiency without breaking references (it takes care of the redirection of references).

Garbage is memory that was once used by objects but will never be read or written by the program again.

Garbage collector (GC) is a background process that provides automatic memory management for the Java environment by taking care of the deallocation of a program’s computer memory resources.

Types of garbage

The types of garbage encountered during the execution of a program are:

  1. Syntactic Garbage - it is clear from the code itself that an object leads to garbage.

  2. Semantic Garbage - whether or not the memory used by an object is garbage can only be determined at runtime.

Benefits of automatic garbage collection in Java

Garbage collection frees the programmer from manually performing memory allocation and deallocation in the program code. As a result, certain categories of bugs are eliminated or substantially reduced:

  • Dangling pointer bugs - a piece of memory is freed, but the objects still have references – one of these references is used in the program.
  • Double free bugs – the program attempts to free a piece of memory that has already been freed.
  • Memory leaks – if a program does not free memory that is no longer referenced by any object, it can lead to memory exhaustion over time.

Drawbacks of garbage collection in Java

Garbage collectors bring some runtime overhead that is out of the programmer’s control. This could lead to performance problems for large applications that scale large numbers of threads or processors, or sockets that consume a large amount of memory.

Code

You can always ask the Java Virtual Machine (JVM) to run a garbage collector:

class HelloWorld {
public static void main( String args[] ) {
HelloWorld h1 = new HelloWorld();
// requesting Java garabage collector
System.gc();
}
}

Conclusion: For large applications, it becomes critical to choose the right garbage collector and tune it to optimize performance.

Free Resources

Attributions:
  1. undefined by undefined