Overview

11 Finding memory-related issues in an app’s execution

This chapter explains how to investigate memory-related problems in Java applications by combining observation, sampling, profiling, and heap-dump analysis. It starts from the idea that memory is a limited shared resource, so poor allocation can make applications slow, trigger excessive garbage collection, or even crash. The chapter emphasizes a practical workflow: first notice abnormal memory usage, then use lightweight sampling to identify suspicious object types, and only then move to profiling or deeper analysis.

Using VisualVM as the main tool, the chapter shows how to sample a running application to see which objects occupy the most memory and whether the issue comes from many small objects or a few very large ones. It then explains how memory profiling can narrow the search to specific classes or packages and reveal where the problematic instances are created. The chapter’s example demonstrates that profiling is most effective when you already have a likely culprit from sampling, and that the profiler can expose allocation counts, live objects, generations, and stack traces tied to object creation.

When an application crashes or cannot be profiled live, the chapter turns to heap dumps as a snapshot of memory at the moment of failure. It describes several ways to obtain a dump, including JVM options, VisualVM, command-line tools like jmap, and programmatic approaches. Once opened in VisualVM, the dump can be inspected through object views or queried with OQL to find large object groups, referers, and leak patterns. The key takeaway is that heap dumps and OQL are especially useful for discovering memory leaks, such as when a long-lived collection keeps references to objects the garbage collector can no longer reclaim.

The memory widget in the Monitor tab in VisualVM helps you to identify if the app spends more memory than usual at any given time. Often, widgets in the Monitor tab, such as CPU and memory consumption, give us clues on how to continue our investigation. When we see that the app consumes an abnormal amount of memory, we may decide to continue with memory profiling the execution.
When we call the endpoint exposed by the provided project da-ch11-ex1, the app creates a large number of instances that consume a considerable part of the app’s memory. We’ll analyze this scenario using a profiler.
We sort the sampled results in descending order by memory occupied. This way, we can see which objects consume most of the memory. We don’t usually look for primitives, strings, and arrays of strings or JDK objects in general. We are mostly interested in finding the object, directly related to our codebase, that is causing the problem. In this case, the Product type (which is part of our codebase) occupies a large part of the memory.
We can sort the sampled results by the number of instances (live objects). This gives us clues on whether some capability creates a large number of objects that are negatively affecting the memory allocation.
To profile for memory allocation, first specify which packages or classes you want to profile, and then start the profiling by pressing the Memory button. The profiler will give you relevant details about the profile types, including used memory, number of instances, the total number of allocated objects, and the number of GC generations.
The profiler shows the stack trace of the code that created the instances of each of the profiled types. This way, you can easily identify what part of the app created the problematic instances.
You can configure the JVM arguments from your IDE. Add the values in the Run/Debug Configurations before starting the application.
You can use VisualVM to open the heap dump file for analysis. Use the Load button in the menu to find the file. Open the file, and VisualVM will display the heap dump as a tab.
Press the Heap Dump button in VisualVM’s Monitor tab to get a heap dump for the selected process. VisualVM opens the dump as a tab, and you can further investigate it or save it anywhere you want.
Using jmap in the command line to get a heap dump. You need to specify the path where the file containing the dump will be saved and the process ID for which you generate the dump. The tool saves the heap dump as a binary file in the requested location.
In the initial screen after opening a heap dump, VisualVM provides a summary of the heap dump, which includes information about the dump itself and the system where the app was running. The view also shows the types that occupy the largest amount of memory.
You can switch to the Objects view, which makes it easier to investigate the instances in the heap dump.
Use sorting on columns to identify which type created a large number of instances or takes up a lot of space. Always look for the first object in your app codebase. In this case, both in number of instances and size, the Product type is the first in the list.
References to an instance. By using the heap dump, you can find, for each instance, what other instances were being referenced at the time the dump was generated. The profiling tool also tells you where a given reference is stored in the code. In this case, ArrayList, which holds over one million references, is a static variable in the Main class.
To switch to the OQL view in VisualVM, choose OQL Console from the drop-down menu in the upper-left corner of the heap dump tab.
Running an OQL query with VisualVM. In the OQL console, write the OQL query in the textbox on the bottom of the window and click the Run button (the green arrow on the left of the text box) to run the query. The results will appear above the text box.
You can access the details about a queried instance (referees and referrers) by clicking it.
Selecting an attribute of a given object type. Just as in Java, you can use the standard dot operator to refer to an attribute of an instance.
Selecting multiple values. You can use JSON formatting to obtain multiple values with one query.
Selecting all the unique referrers for instances of a type shows you if there’s one object that prevents the GC from removing the instances from memory. This can be a quick way to identify a memory leak.

Summary

  • An app with capabilities that are not optimized for memory allocation can cause performance problems. Optimizing the app to wisely allocate (avoid spending unnecessary memory space) the data in memory is essential to an app’s performance.
  • A profiling tool allows you to sample and profile how the memory gets occupied during an app’s execution. This can help you identify unoptimized parts of your app and provides you with details on what can be improved.
  • If new object instances are continuously added to the memory during execution but the app never removes the references to new instances, the GC won’t be able to delete the references and free the memory. When the memory gets fully occupied, the app cannot continue its execution and stops. Before stopping, the app throws an OutOfMemoryError.
  • To investigate an OutOfMemoryError, we use heap dumps. A heap dump collects all the data in the app’s heap memory and allows you to analyze it to figure out what went wrong.
  • You can start your app using a couple of JVM arguments to instruct it to generate a heap dump at a given path if the app fails with an OutOfMemoryError.
  • You can also get a heap dump by using a profiling tool or a command-line tool such as jmap.
  • To analyze a heap dump, load it in a profiling tool such as VisualVM, which allows you to investigate the instances in the dump and their relationships. This way, you can figure out what part of the app is not optimized or has memory leaks.
  • VisualVM offers more advanced ways to analyze the heap dump, such as OQL queries. OQL is a querying language similar to SQL that you use to retrieve data from a heap dump.

FAQ

What kinds of memory-related problems does this chapter focus on?

This chapter focuses on identifying memory allocation issues in a Java application’s execution, including excessive memory use, memory leaks, and crashes caused by running out of heap space.

Why can poor memory management slow down an application even if it doesn’t crash?

When an app allocates memory inefficiently, the garbage collector may run more often. That increases CPU usage and can make the application slower even before it runs out of memory.

What is the first step in investigating a suspected memory problem while the app is still running?

The first step is memory sampling. In VisualVM, you use the Sampler tab and the Memory option to get a high-level view of what object types are occupying memory.

What should you look for in a memory sampling result?

You should sort by occupied memory and by number of instances, then look for the first object type from your own codebase that stands out. Usually, you ignore primitives, strings, arrays of strings, and common JDK types because they often do not reveal the root cause.

When is memory profiling more useful than sampling?

Profiling is useful when sampling tells you which type is consuming memory, but not which part of the code creates those objects. Profiling adds more detail, including allocation locations and other statistics about the profiled types.

What information does memory profiling provide beyond live objects?

It can show the total number of instances created, the number of live objects, and how many GC generations those objects survived. It can also reveal the stack trace or code location where the instances were created.

When should you use a heap dump instead of profiling?

Use a heap dump when the app has crashed or when you cannot attach a profiler to the running process. A heap dump gives you a snapshot of memory at the time of failure, which is especially useful for analyzing OutOfMemoryError problems.

How can you configure a Java app to generate a heap dump automatically on OutOfMemoryError?

Use JVM arguments such as -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath=heapdump.bin. This tells the JVM to create a heap dump automatically and save it to the specified path when memory is exhausted.

How can you obtain a heap dump for a running process?

You can use VisualVM’s Heap Dump button in the Monitor tab, or use command-line tools like jmap. With jmap, you first find the process ID with jps, then run a command such as jmap -dump:format=b,file=C:/DA/heapdump.bin 25320.

How does the chapter suggest finding the root cause of a memory leak in a heap dump?

Open the dump in VisualVM, switch to the Objects view, sort by instance count and memory usage, and inspect the first application-specific type. Then check its referrers to see what is keeping the objects alive; in the example, a static ArrayList in Main keeps references to many Product instances and prevents GC from collecting them.