Trusted answers to developer questions

Garbage collection in Java

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Garbage collection (GC) is the process of freeing up (or collecting) unused memory from the heap. This freeing-up process is necessary because as a program continues to execute, it creates objects dynamically on the heap, which decreases the amount of free space that can be allocated to a newly created object.

Garbage collection in Java has three phases:

1. Marking

In this phase, those parts of the memory which are in use, and those t​hat are not, are identified. An object which has no reference to it is considered to be unreachable and is, therefore, marked unused. Since checking all of the memory and marking it consumes a lot of time, the Java Virtual Machine (JVM) makes this process more efficient by dividing the heap into three generations:

  1. Young
  2. Old (or Tenured)
  3. Permanent

The young generation is further divided into three spaces:

  1. Eden
  2. First survivor space
  3. Second survivor space

2. Deletion

Initially, the survivor spaces are empty, ​and every new object is allocated memory in Eden. Once Eden gets completely filled, a minor garbage collection is performed; the unreferenced objects are deleted and the survivors are copied to the first survivor space.

When Eden fills up again, another minor GC is performed, both on Eden and the first survivor space. Unused objects in both these spaces are deleted, while the survivors are copied to the second survivor space. Those objects which are copied from the first survivor space have their age incremented.

This process continues, but with the survivor spaces switching, i.e., every time Eden runs out of memory, the first and second survivor spaces alternately get cleared during a minor GC. The slides below demonstrate this process:

Eden not completely filled
1 of 8

3. Promotion

Objects in the survivor spaces, whose age is above the set age threshold, are promoted to the old generation. When the need arises, a major GC will be performed on the old generation to free up space.

Objects do not get promoted to the permanent generation as it contains metadata about the classes that are in use by the Java application. Some metadata may be cleared (collected) if a class is identified as no longer being in use,​ or if a new class requires space in the generation.

RELATED TAGS

garbage
collection
java
memory
heap
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?