Java Garbage Collection Basics

Objects dynamically created using a new operator are deallocated automatically. The technique that accomplishes this is called garbage collection. It works like this: When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

How Does Automatic Garbage Collection Work?

Automatic garbage collection works by looking at heap memory, identifying which objects are being referenced and which are not, and deleting the unused objects. This is widely known as the “Mark and Sweep Algorithm.”

The process of deallocating memory is handled automatically by the garbage collector in two steps:

Step 1: Marking

This is first step where the garbage collector identifies which pieces of memory are in use and which are not and marks those objects that are not referenced anymore.

Garbage Collection Marking

Source: Oracle Java Docs

Step 2: Deleting

In this step, all the marked objects, which are not referenced anymore, in Step 1 are deleted and reclaim the memory.

This can be done in two types:

2a) Normal Deletion

In this deletion, the memory allocator holds references to blocks of free space where a new object can be allocated, as shown in figure below.

Garbage Collection-Normal Deletion

Source: Oracle Java Docs

2b) Deletion With Compacting

In this process, instead of just removing objects from memory, the remaining objects will be compacted to further improve performance, in addition to deleting unreferenced objects. By moving referenced object together, this makes new memory allocation much easier and faster.

Garbage Collection- Compact Deletion

Source: Oracle Java Docs

For further information on how garbage collection works, please refer to this Oracle Java Docs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s