CodeGym /Courses /JAVA 25 SELF /Memory analysis tools: jmap, jvisualvm

Memory analysis tools: jmap, jvisualvm

JAVA 25 SELF
Level 64 , Lesson 3
Available

1. jmap: command-line magic

The automatic garbage collector is great, of course. But even Java applications can “leak” (OutOfMemoryError), run slowly, or suffer unexpected slowdowns due to improper memory usage. The reasons can vary:

  • Memory leaks: objects that should have been collected keep “living.”
  • Excessive amounts of data in collections.
  • Bugs in caching logic.
  • Unreleased resources (for example, streams, files).

Your goal is to learn to find such problems quickly. Otherwise you risk becoming not a programmer but a “bug developer”!

What is jmap?

jmap is a utility included in the standard JDK. It lets you obtain a “snapshot” (heap dump) of a running Java process’s memory. You can then open this snapshot in other tools and see which objects occupy memory, how many there are, and who references them.

Heap dump is like a photograph of your heap: all objects it contains, their types, relationships, and sizes.

How to use jmap

Find the process PID

First, you need to find the process identifier (PID) in which your Java application is running. You can do this in various ways:

Via jps (another utility from the JDK):

jps -l

You will see a list of Java processes and their PIDs.

Through Task Manager or ps on Linux.

Capture a heap dump

jmap -dump:format=b,file=heap.bin <PID>
  • format=b — binary format (suitable for analysis).
  • file=heap.bin — the file name to save the dump to.
  • <PID> — the process identifier.

Example:

jmap -dump:format=b,file=heap.bin 12345

What to do with a heap dump?
Usually you analyse the dump in graphical tools (for example, jvisualvm or Eclipse MAT), because searching for objects manually in a binary file is advanced acrobatics and a bit of masochism.

Other jmap capabilities

View heap statistics:

jmap -heap <PID>

Shows information about the heap: size, GC in use, state.

Class histogram:

jmap -histo <PID>

Shows per-class statistics: how many objects of each type and total size.

Example output:

# Class Count Bytes
1
[C
1200 48000
2
java.lang.String
1000 32000
3
java.util.HashMap
200 12800

This already gives you an idea: if you suddenly have millions of objects of some type, that’s a reason to investigate.

2. jvisualvm: a visual memory analyzer

jvisualvm is a graphical program included with the JDK (look in the bin folder). It allows you to connect to local (and sometimes remote) Java processes, monitor them in real time, take a heap dump, view memory, threads, GC, CPU statistics, and even profile code execution.

If you like clicking with a mouse and looking at pretty charts, this is your tool.

How to start jvisualvm

From the command line (or via a shortcut on Windows):

jvisualvm

A window will open where you will see a list of all local Java processes.

Key features of jvisualvm

Real-time memory monitoring

  • Select a process in the list on the left.
  • Switch to the Monitor tab.
  • You will see charts for heap usage, CPU, and counts of threads and classes.

Example:

jvisualvm-monitor

Heap Dump (memory snapshot)

  • On the Monitor panel, click Heap Dump.
  • After a few seconds, a tab with dump analysis will appear.
  • You will see a list of all classes, object counts, and their total size.

Finding “heavy” objects

  • Sort by size or count.
  • If you see that some type (for example, ArrayList or String) takes too much memory, that’s a reason to investigate.

Reference analysis (Reference Graph)

  • Click a class to see who references its objects.
  • You can drill down to the root: why the object is not being collected by GC.

Thread analysis

  • The Threads tab shows all threads and their state.
  • You can identify “stuck” or overly active threads.

Profiling

  • The Profiler tab lets you measure which methods consume the most time or memory.
  • This is deep analysis, but for finding memory leaks the first steps are usually enough.

3. Practice: analyzing a memory leak

Example code with a leak

import java.util.ArrayList;
import java.util.List;

public class MemoryLeakDemo {
    // Static collection — a classic!
    private static final List<String> bigList = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1_000_000; i++) {
            bigList.add("String number " + i);
            if (i % 100_000 == 0) {
                System.out.println("Added: " + i);
                Thread.sleep(500); // Give some time for analysis
            }
        }
        System.out.println("Done! Do not close the application, open jvisualvm.");
        Thread.sleep(600_000); // 10 minutes — time for analysis
    }
}

What’s happening?

  • We create a static list and add a million strings to it.
  • After finishing the additions, the program “idles” (waits) so that you can attach analysis tools to it.

Analysis with jvisualvm

  1. Run the program.
  2. Open jvisualvm and select the process.
  3. On the Monitor tab, look at the memory chart.
    • If everything is fine, memory should be released after GC.
    • If there’s a leak, memory only grows.
  4. Take a Heap Dump.
  5. See which objects occupy the most memory.
    • In our case — java.util.ArrayList and java.lang.String.
  6. Click an object to see who references it.
    • You’ll see it’s the static field bigList.

How to fix it?

  • Remove unnecessary elements from collections; limit their growth.
  • Null out references to heavy objects when they’re no longer needed.
  • Don’t keep large collections in static if they aren’t needed continuously.

4. Other tools: Eclipse MAT, jconsole

Eclipse Memory Analyzer (MAT)

Eclipse MAT is a free yet powerful tool for analyzing heap dumps. With it you can see which objects occupy memory and which ones retain others — the so‑called retained set. This lets you pinpoint where the leak hides.

The tool can build detailed reports about suspicious objects (leak suspects) and can easily handle gigantic dumps of several gigabytes.

It’s simple: you take a heap dump with jmap or jvisualvm, open it in MAT, click the Leak Suspects Report button — and get a ready‑made report with potential issues already highlighted.

jconsole

jconsole is a simple and convenient tool for observing the JVM in real time. It shows how much memory is used, how loaded the CPU is, how many threads are running, and how the garbage collector behaves.

Unlike more advanced tools like VisualVM, jconsole does not analyze heap dumps, but it’s great for quick diagnostics — when you need to understand at a glance what’s happening inside the application right now.

5. Common mistakes in memory analysis

Error #1: You dump the wrong process. A machine often runs many Java applications, and it’s easy to confuse the PID. Check via jps and make sure you’re analyzing your program.

Error #2: You expect to see a “leak” where there isn’t one. GC may not reclaim objects immediately — sometimes memory is released only after a Full GC. Don’t panic if memory isn’t freed after one iteration — look at the trend.

Error #3: You don’t account for the impact of static/cached objects. Many leaks are due to objects being stored in static fields or global collections. Check who references “heavy” objects — it’s often static.

Error #4: You don’t use profiling over time. A heap dump is good, but sometimes it’s important to look at memory growth over time (the charts in jvisualvm). If memory steadily grows, there’s a reason to investigate.

Error #5: You don’t remove listeners/handlers. If you subscribed to an event but didn’t unsubscribe, the object will “live” in memory even if you no longer use it.

Tip: Don’t be afraid to experiment with the tools! Take dumps, look at charts, click through objects — only then will you learn to “feel” your program’s memory and quickly find problems.

1
Task
JAVA 25 SELF, level 64, lesson 3
Locked
Capturing a memory dump with jmap – Bear's digital snapshot 🐻
Capturing a memory dump with jmap – Bear's digital snapshot 🐻
1
Task
JAVA 25 SELF, level 64, lesson 3
Locked
Viewing class statistics with jmap – Digital Zoo Inventory 🐒🐘🐆
Viewing class statistics with jmap – Digital Zoo Inventory 🐒🐘🐆
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION