Book Image

Java Memory Management

By : Maaike van Putten, Dr. Seán Kennedy
Book Image

Java Memory Management

By: Maaike van Putten, Dr. Seán Kennedy

Overview of this book

Understanding how Java organizes memory is important for every Java professional, but this particular topic is a common knowledge gap for many software professionals. Having in-depth knowledge of memory functioning and management is incredibly useful in writing and analyzing code, as well as debugging memory problems. In fact, it can be just the knowledge you need to level up your skills and career. In this book, you’ll start by working through the basics of Java memory. After that, you’ll dive into the different segments individually. You’ll explore the stack, the heap, and the Metaspace. Next, you’ll be ready to delve into JVM standard garbage collectors. The book will also show you how to tune, monitor and profile JVM memory management. Later chapters will guide you on how to avoid and spot memory leaks. By the end of this book, you’ll have understood how Java manages memory and how to customize it for the benefit of your applications.
Table of Contents (10 chapters)

Being eligible for GC

We already know that objects on the heap are removed when they are no longer needed. The right question to ask, then, would be, when are objects no longer needed?

That question is easy to answer but leads to a complex problem at the same time. Let’s first have a look at the answer: objects on the heap are no longer needed when they don’t have a connection to the stack.

Objects don’t have a connection to the stack when the stack doesn’t store the reference to the object in a variable. Here is a simple example:

Object o = new Object();
o = null;

In the first line, we create the object, which gets created on the heap. The o variable holds a reference to an object of type Object on the stack. We use the object because we have the reference stored. In this case, we are printing it on the second line of the example, which is clearly a rather silly output since the toString() method of Object is only...