Your application is using too much memory, but when you check the heap, it’s not even full. Performance drops, not only in your own application, but in the device or container as a whole. You may even see the ‘disappearing service’ syndrome, where the operating system or container manager kills a rogue process that is threatening to freeze the device.

Chances are, the problem isn’t in the heap at all. The heap is only one of the JVM’s several memory pools.

Off-heap and metaspace analysis is notoriously tricky. There are plenty of good tools for heap analysis, but if the problem isn’t in the heap, they’re unlikely to give you the answers you need.

Can AI help you?

In this article, we’ll take a look at off-heap memory and what it’s used for, before working through a case study to understand how deterministic AI can help diagnose off-heap problems.

Understanding Java Off-Heap Memory and the JVM Memory Model

The diagram below shows a simplified version of the JVM memory model:

Fig: JVM Memory Model

1. Heap Memory

Heap memory, consisting of the Young Generation and the Old Generation, is a central storage area for all objects created by the application. It’s managed by the JVM, and its size can be configured using command-line arguments when the JVM is invoked. Heap space is regularly cleaned and compressed by the garbage collector.

2. Key JVM Native Memory Areas: Metaspace, Thread Stacks, Code Cache, and Direct Buffers

Off-heap memory, also known as native memory, is managed by the operating system. Space for native memory is over and above the limit set for the heap.

Important memory pools in native memory include:

  • Metaspace holds metadata related to classes, bytecode for methods, and other static data. In older JVMs, this information was held in a heap area called the PermGen.
  • Thread Space contains the stack space for each running thread.
  • Code Cache contains pre-compiled machine code for ‘hot spots’ – frequently used methods.
  • Direct Buffers allow access to operating-system managed buffers for faster I/O.
  • GC is an area reserved for the garbage collector’s internal use.
  • JNI is used by the Java Native Interface.
  • Misc is reserved for the JVM’s internal use.

For a more comprehensive overview of JVM internals, I’d suggest watching JVM Explained in 10 Minutes.

If the application is using too much off-heap memory, the most likely culprits are the metaspace or the direct buffer area. Memory pressure in the thread space usually results in a different problem: the application may crash with the error OutOfMemoryError: Unable to create new native threads.

Java Native Interface (JNI) can also cause native memory pressure, but most modern applications use the Java Foreign Function and Memory API instead of the older JNI interface.

Common Symptoms of Java Native Memory Issues

Most memory problems occur in the heap, and the symptoms of heap pressure and native memory pressure are similar. Without diagnostics, it’s hard to tell the difference.

When memory of any category is over-utilized, we may see:

  • Slow response times;
  • Increased CPU usage;
  • Reduced throughput and/or high latency;
  • Application crashes.

In addition to these, if the problem is in native memory:

  • The device or container as a whole may become sluggish and unresponsive;
  • The operating system may kill the application to avoid the entire device crashing or freezing due to lack of memory.

How to Troubleshoot Java Off-Heap and Metaspace Memory Issues

Let’s look at the steps we would follow to diagnose off-heap memory issues.

1. Identify Whether the Memory Issue Is in the Java Heap or Off-Heap Memory

When we encounter poor performance and suspect memory issues, we need to first establish whether the problem is in the heap or in native memory. The simplest way to do this is to first check the application’s total memory usage using the top command in Linux, or Task Manager in Windows.

Later, we’ll be looking at a case study where Tomcat is using excessive native memory. The line on the top output relating to this process looks like this:

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
   5318 tomcat    20   0 5523172   1.5g  22916 S   6.2  45.8   3:30.50 java 

The process is using 1.5GB of resident memory, and a further 5MB of virtual memory.

We can see how much of this is heap memory using jcmd, one of the diagnostic commands packaged with the JDK.

$ sudo jcmd 5318 GC.heap_info
119923:
garbage-first heap total 129024K, used 39602K [0x00000000cb800000, 0x0000000100000000)
region size 1024K, 28 young (28672K), 3 survivors (3072K)
Metaspace used 17764K, committed 18240K, reserved 1114112K
class space used 1751K, committed 1984K, reserved 1048576K

We see the process has a total heap space of approximately 129MB, only 39.6MB of which is currently in use. This means the amount reserved for the heap occupies only 129MB of the approximately 1.6GB used in total for the application. The 39.6MB in use is also far smaller than the heap space allocated.

This is an extreme case, but we can see immediately that the memory problem is in native memory, not the heap.

This command also tells us how much of the metaspace and class space are currently being used. If the problem is in the metaspace, we’ll be able to see this immediately.

2. Identify the JVM Native Memory Area Causing Excessive Usage

To do this, we need to enable native memory tracking (NMT)  on the JVM command line. This gives us a text file showing memory usage by category.

2.1 Activating Native Memory Tracking

To enable NMT we can use either the options:

-XX:NativeMemoryTracking=detail

Or the option:

-XX:NativeMemoryTracking=summary

The first option isn’t suitable for long-term use in production, since it has a high overhead, but it does give more information for hard-to-solve cases.

To extract a snapshot of native memory usage to a file while an application is running, we need to run this command:

jcmd <pid> VM.native_memory detail >> <filename>

or

jcmd <pid> VM.native_memory summary >> <filename>

Usually, we’d also want to track which areas are growing and which are stable. To do this, we’d run the command several times at intervals.

2.2 How to Use Java Native Memory Tracking (NMT) to Analyze JVM Memory Usage

Native memory tracking (NMT)  lists the amount of memory used in each of the following categories:

CategoryBrief description
Java HeapAllocated for Java objects and arrays.
ClassIncludes metadata for classes and compressed class space.
ThreadUsed by JVM threads, including thread stacks and associated structures.
CodeCode cache containing compiled JIT-compiled methods and related data.
GCUsed by garbage collection, including GC structures and bookkeeping.
CompilerUsed by the JIT compiler.
InternalInternal JVM allocations, such as JVM data structures and management facilities.
SymbolUsed for JVM symbols, including class and method names.
Native Memory TrackingConsumed by the NMT process to track native allocations.
Arena ChunkMemory allocated in chunks for JVM arena-based allocation.
LoggingUsed by JVM logging facilities.
ArgumentsUsed to store JVM command-line arguments and related configuration.
ModuleUsed by the Java module system.
SafepointUsed for JVM safepoint management.
SynchronizationUsed for JVM synchronisation and locking structures.
ServiceabilityUsed by JVM diagnostic and serviceability facilities.
MetaspaceDepending on the JDK/report format, may appear as a separate category or as part of Class; holds class metadata.
OtherNative allocations not accounted for in the other named categories, including direct buffer memory.

This gives an idea of what to look for in the application. The two most likely culprits are:

2.3 Analyzing NMT files using GCeasy

The accumulated NMT file may be very long, and analyzing off-heap usage can become tedious. An excellent tool for fast analysis of NMT files is GCeasy. GCeasy is primarily used for analyzing GC logs, but if we load an NMT file as a .txt,  we get problem analysis, as well as interactive charts and graphs such as the one below:

Fig: GCeasy Analysis of NMT Output

For more information about NMT tracking, and more detailed GCeasy reports, see Understanding NMT Tracking in Java.

3. Use Java Flight Recorder (JFR) to Diagnose Native Memory Issues

JFR is an extremely useful tool for tracking events within a running application.

3.1 How to Enable JFR

It can be enabled on the command line, for example:

-XX:StartFlightRecording=name=Profiling,filename=<path>,
settings=profile,dumponexit=true

This is often followed by a comma and a comma-separated list of specific events to be tracked. The file may only be written when the recording terminates, although we can use jcmd to force a dump:

jcmd <pid> JFR.dump filename=<path>

We can also use jcmd to start and stop a recording of a running application:

jcmd <pid> JFR.start settings=profile
jcmd <pid> JFR.stop name=<path>

3.2 Important JFR Events for Diagnosing Java Native Memory Issues

When we’re troubleshooting native memory issues, these events are useful:

JFR eventWhat it helps identify
jdk.DirectBufferStatisticsDirect buffer pool capacity, memory used, and buffer count
jdk.NativeMemoryUsageJVM native-memory usage, where supported by the JDK
jdk.NativeMethodSampleSampled native method execution
jdk.ClassLoaderStatisticsClass-loader statistics
jdk.ClassLoadIndividual class loading
jdk.ClassUnloadIndividual class unloading

The flight recording is a binary file, so we need a tool such as yCrash or JMC to interpret it.

How Deterministic AI Simplifies Java Off-Heap and Metaspace Analysis

Both NMT and JFR files are usually rather long, and trying to analyze them can be tedious. If we load them directly into AI, we may get good results – or, as sometimes happens, we may get hallucinations that send us off on the wrong track and waste time. Also, since the files may be huge, loading them is likely to become expensive in tokens.

Deterministic AI gives us the best of both worlds. This is how it works:

Fig: Deterministic AI Workflow

We upload our JFR recording into yCrash, which parses the log and, on request, forwards a curated set of relevant facts to the LLM. We then use AI to carry out further analysis. This uses far fewer tokens and makes sure the underlying facts presented to the AI are accurate, removing the possibility of hallucinations.

Case Study: Diagnosing Java Metaspace and Direct Buffer Memory Leaks Using AI

Let’s now work through a case study illustrating how deterministic AI can speed up the diagnostic process.

1. Simulating Metaspace and Direct Buffer Memory Leaks in Tomcat

We used Tomcat for the case study, since it’s well-known that if all references aren’t cleared in a destroy() method, class loader leaks often occur when the application is redeployed.

We wrote a small web app that not only causes a class loader leak, but also creates excessive direct buffers.

The web app looks like this:

package com.example;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
// ==================================================
// Webapp that causes a class loader leak on redeploy
// and also uses excess direct buffer memory
// ==================================================
public class InitDemoServlet extends HttpServlet {
Thread backgroundThread;
@Override
public void init() throws ServletException {
System.out.println("=================================");
System.out.println("InitDemoServlet init() invoked");
System.out.println("Time: " + new Date());
System.out.println("=================================");
// The init method starts a thread that loops forever
// Since there is no destroy() method, the thread will
// continue even if the webapp is undeployed
// causing a classloader leak.
// ==========================================================
backgroundThread = new Thread(() -> {
// The direct buffer is added to this array
// ensuring there will always be a reference to it,
// preventing the space from being reclaimed.
// ===============================================
ArrayList<ByteBuffer> a = new ArrayList<>();
try {
while (true) {
// The thread never terminates.
// This means it will progressively fill up
// native memory
ByteBuffer directBuffer =
ByteBuffer.allocateDirect(1000000);
a.add(directBuffer);
Thread.sleep(60000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
},"HangingThread");
backgroundThread.start();
}
@Override
// Dummy doGet method that does nothing
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
}
}

The init() method, which Tomcat calls when the class is instantiated, creates a thread that is never destroyed. The thread loops indefinitely, creating a direct buffer and adding a reference to it into an ArrayList.

Since there is no destroy() method to kill the thread when the web app is undeployed, it will cause a class loader leak as well as filling up the direct buffer area.

By default, Tomcat uses lazy instantiation. The class is only instantiated when an HTTP request requires it. To override this, we need to add the line <load-on-startup>1</load-on-startup> to the web.xml file, as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>InitDemoServlet</servlet-name>
<servlet-class>
com.example.InitDemoServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>InitDemoServlet</servlet-name>
<url-pattern>/initdemo</url-pattern>
</servlet-mapping>
</web-app>

We also needed to change the Tomcat command line to include:

  • Native memory tracking
  • JFR recording. In the JFR recording, we included the following events:
    • DirectBufferStatistics
    • NativeMemoryUsage
    • NativeMemoryUsageTotal
    • NativeMethodSample
    • ClassLoaderStatistics
    • ClassLoad
    • ClassUnload

To achieve this, we set the Tomcat configuration to include the parameters shown below.

Environment="JAVA_TOOL_OPTIONS=-XX:MaxDirectMemorySize=3G
-XX:StartFlightRecording=name=Profiling,filename=/home/jill/shared/logs/tomcat.jfr,
settings=profile,,dumponexit=true,jdk.DirectBufferStatistics#enabled=true,
jdk.NativeMemoryUsage#enabled=true,jdk.NativeMemoryUsageTotal#enabled=true,
jdk.NativeMethodSample#enabled=true,jdk.ClassLoaderStatistics#enabled=true,
jdk.ClassLoad#enabled=true,jdk.ClassUnload#enabled=true
-XX:NativeMemoryTracking=detail -Xlog:gc*,gc+age=trace,gc+heap=debug:
file=/home/jill/shared/logs/tomcat.log:time,uptime,level,tags"

We then ran Tomcat for a few hours. From time to time, we redeployed the app. We also periodically extracted NMT statistics using jcmd.

2. Analyzing Java Flight Recorder (JFR) Data Using AI

We dumped the JFR recording to a file and submitted it to yCrash, which was configured to interface with a famous LLM. This returned an AI summary of the application, with tabs for viewing further information.

The summary gave a warning that full GC events were running back-to-back, even though the heap was not full. Events were triggered by System.gc(). It also detected that there is a class loader leak.

Fig: yCrash AI Overview

A quick look at the GC tab of the report confirmed this:

Fig: GC Events Running Frequently When Heap is Not Full

This is typical of direct buffer leaks: when the direct buffer area is almost full, the JVM itself calls System.gc() in the hopes that the references that are holding the space can be garbage collected.

At the end of the AI summary, it gave us the option to dig deeper in AI mode. Selecting this allowed us to submit a question and optionally upload a file to yCrash Deterministic AI.

Fig: yCrash AI Option

We’re simulating a situation which would almost certainly result eventually in the operating system killing our application when the device ran short of space. We therefore submitted the following question:

The JFR recording is from a Tomcat server. This server is occasionally killed by the operating system’s OOM killer, although this didn’t happen during the recording. Can you shed any light on why this is happening? Attached is the output of NMT tracking over the same period.

We attached our file containing NMT tracking taken over the same period as the JFR file.

yCrash Deterministic AI responded as follows:

Fig: Initial AI Analysis by yCrash Deterministic AI

Summarizing this response, yCrash Deterministic AI has detected massive growth in the ‘Others’ area, which it suggests is probably caused by a direct buffer. Since the application is using 95% of the available memory on the device and is growing, it’s a natural target for the OOM killer.

yCrash Deterministic AI makes some suggestions on what to investigate and what steps we can take to mitigate the problem in the meantime.

It then allows us to ask further questions.

3. Correlating ClassLoader Leaks with Direct Buffer Memory Growth

We next asked yCrash Deterministic AI the following question:

Is there any correlation between the repeated WAR redeployment cycle and increases in the “Other” category size?

yCrash Deterministic AI responded as follows:

Fig: Correlating the Two Problems

yCrash Deterministic AI suggests that the app causing the class loader leak may be retaining direct buffer space, and suggests further action.

4. Identifying Evidence of a Java ClassLoader Leak

Next, we asked yCrash Deterministic AI:

Is there any evidence of a classloader leak?

yCrash Deterministic AI responded as follows:

Fig: Evidence of a Class Loader Leak

yCrash Deterministic AI identified:

  • The actual classes that have up to 100 instances in memory due to having been loaded but never unloaded;
  • The pattern from the NMT data strongly suggests a class loader leak;
  • The entry to look for in the Tomcat logs that will point directly to the offending web app.

5. Assessing the Risk of Direct Buffer Memory Leaks

We’ve identified that we have two problems: a class loader leak, and a direct buffer leak. In order to prioritize troubleshooting tasks, we asked:

Which problem presents the greater immediate risk?

yCrash Deterministic AI replied as follows:

Fig: Risk Analysis

yCrash Deterministic AI prioritizes the direct buffer leak, since in a fairly short period it has already accumulated almost 2GB of memory, putting the device at immediate risk of running out of memory.

6. Developing a Diagnostic Strategy to Identify Memory Leak Root Causes

The JFR and NMT have confirmed that we need to urgently address a direct buffer leak, and we also need to address the class loader leak before the problem becomes severe.

We asked yCrash Deterministic AI to map out the exact recommended steps for finding the root cause of the problem.

Based on your analysis of the JFR recording and NMT sampling data, recommend additional diagnostic steps to establish the precise causes of both memory leaks.

yCrash Deterministic AI responded with an actionable diagnostic roadmap.

Since it’s very detailed and therefore quite long, we are reproducing only the first section of yCrash Deterministic AI’s reply.

Fig: Section of Diagnostic Roadmap Produced by yCrash Deterministic AI

Thanks to deterministic AI, we were able to very quickly identify the problem and produce an action plan for further analysis.

Conclusion: Simplifying Java Off-Heap and Metaspace Troubleshooting with AI

Most memory problems relate to the heap, but this is not always the case. Off-heap and metaspace analysis can be tricky and time-consuming.

JFR and NMT tracking are the two most important tools for diagnosing memory problems outside the heap. Both produce a large volume of information, which is tedious to analyze manually and expensive in tokens if we load it directly into an LLM.

yCrash’s deterministic AI option gives us the power of AI without the high cost and risk of defective conclusions.

In this article, we demonstrated a Tomcat web app that caused native memory issues. We loaded a JFR recording into yCrash and requested AI analysis. By supplementing this with an NMT tracking report, we were able to diagnose the problem and get precise instructions on how to track the issue to its root cause.