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)

Avoiding memory leaks

The best way of avoiding a memory leak is to write code that does not contain any leaks in the first place. In other words, objects that we no longer need should not have connections back to the stack, as that prevents the garbage collector from reclaiming them. Before we get into techniques that help you avoid leaks in your code, let us first fix the leak presented in Figure 7.1. Figure 7.6 presents the leak-free code:

Figure 7.6 – Leak-free program

Figure 7.6 – Leak-free program

In Figure 7.6, the infinite loop remains. However, lines 19 to 23 are new. In this new section, we increment an i local variable every time we add a Person reference to the ArrayList object. Once we have done this 1,000 times, we re-initialize our list reference. This is crucial as it enables the garbage collector to reclaim the old ArrayList object and the 1,000 Person objects referred to from the ArrayList object. In addition, we reset i back to 0. This will solve the leak. ...