Garbage Collection

This lesson explains the working of garbage collection works in Java.

We'll cover the following...

Question # 1

What is a garbage collector?

Unlike other languages, Java takes off the load of memory management from the developer. The crux is Java determines what objects are no longer used and reclaims the memory for future use. Java's garbage collection tracks live objects and everything else is assumed to be garbage. Garbage collector is the program running in the background that looks into all the objects in the memory.

Java ships with several garbage collectors. More specifically, these are different algorithms that run in their own threads. Each works differently and has pros and cons. The most important thing to keep in mind is that all garbage collectors stop the world. That is, your application is put on hold or paused, as the garbage is collected and taken out. The main difference among the algorithms is how they stop the world. Some algorithms sit completely idle until the garbage collection is absolutely needed and then pause your application for a long period while others do most of their work concurrently with your application and thus need a shorter pause during stop the world phase. The best algorithm depends on your goals: are you optimizing for throughput where long pauses every now and then are tolerable or you are optimizing for low latency by spreading it out and having short pauses all along.

Question # 2

Explain the garbage collection process in Java.

  • Whenever a new object is created, it is allocated its space in the Eden memory. The Eden memory is limited and fills up fast. Initially, both the survivor spaces are empty. Let's call them survivor space A and B to distinguish between them. ...