Understanding Java Garbage Collection

Thilina Ashen Gamage
Platform Engineer
Published in
9 min readAug 31, 2018

--

Java Garbage Collection (GC) is the process of tracking the live objects while destroying unreferenced objects in the Heap memory in order to reclaim space for future object allocation. To understand GC well, it is good to have a solid understanding of the basics of JVM Architecture and Java Memory Model.

Importance of understanding GC

GC enables faster development with less boilerplate code (no need for manually allocating and releasing memory) and eliminates memory-related issues. However, in reality, JVM performs garbage collection by creating and removing too many objects, which results in serious performance problems. In order to effectively manage garbage collection and memory issues in JVM, you need to understand how garbage collection really works under the hood.

How GC works

Java Garbage Collector runs as a Daemon Thread (i.e. a low priority thread that runs in the background to provide services to user threads or perform JVM tasks). From time to time, it looks into all the objects in Heap memory and identifies objects that are no longer referenced by any part of your program (such unreferenced objects can no longer be reachable by the application code). Then all these unreferenced objects are destroyed and space will be reclaimed for newly-creating objects.

We can explain the Java garbage collection process using the following simple approach.

  1. Mark: Identifying objects that are…

--

--

Thilina Ashen Gamage
Platform Engineer

Advocate of Cloud, Microservices, & Clean Code | 1.5M+ Reach | For more exciting content, stay in touch: https://medium.com/@ThilinaAshenGamage