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)


In this chapter, we started by examining how primitives are stored in memory. Primitives are predefined types that come with the language and can be stored on both the stack (local variables) and on the heap (instance variables). It is easy to identify primitives as they have all lowercase letters.

In contrast, objects are only stored on the heap. In discussing objects, it was necessary to distinguish between references and the objects themselves. We discovered that while references can be of any type (interface, abstract class, and class), objects themselves can only be of proper, concrete classes, meaning the class must not be abstract.

Manage object references with care. If not managed properly, you could end up with escaping references. Java uses call-by-value, which means a copy is made of the argument passed or returned. Depending on whether the argument is a primitive or reference, it can have major implications. If it’s a copy of a reference to a mutable type, then the calling code can change your supposedly private data. This is not proper encapsulation.

We examined code with this issue and associated diagrams of the stack and heap. The solution is to use defensive copying, that is, copying the object contents both on the way in and on the way out. Thus, the references and the objects they refer to remain private. Lastly, we detailed the code solution and associated diagrams of the stack and heap.

In the next chapter, we are going to take a closer look at the heap, the area of memory where objects live.