1. Overview

Profiling an application provides deep insight into its behavior during the runtime. There are various popular profilers in the Java ecosystems such as NetBeans Profiler, JProfiler, and VisualVM for general-purpose profiling. NetBeans Profiler offers great functionality for free.

In this tutorial, we’ll dive into how to use the NetBeans profiler API programmatically by creating a sample project, taking a heap dump, and analyzing it using the NetBeans Profiler API.

2. NetBeans Profiler

The NetBeans IDE offers a free profiler to analyze Java applications. It provides functionality to assess the CPU performance and memory usage through an intuitive embedded UI in the IDE.

However, NetBeans Profiler also makes its profiling API accessible for programmatic use. This could be advantageous for automating heap dump analysis without much reliance on GUI tools.

The heap dump is the memory snapshot of an application at a period in time. It’s a good indicator to gain insight into memory usage because it includes live objects in the memory, their classes and fields, and references between objects.

3. Example Setup

To use the NetBeans Profiler API, let’s add its dependency to the pom.xml:

<dependency>
    <groupId>org.netbeans.modules</groupId>
    <artifactId>org-netbeans-lib-profiler</artifactId>
    <version>RELEASE220</version>
</dependency>

This dependency provides various classes such as JavaClasses and Instances to help us analyze classes, the number of instances created, and the memory used.

Next, let’s create a simple project and analyze it’s heap dump:

class SolarSystem {

    private static final Logger LOGGER = Logger.getLogger(SolarSystem.class.getName());

    private int id;

    private String name;

    private List<String> planet = new ArrayList<>();

    // constructors

    public void logSolarSystem() {
        LOGGER.info(name);
        LOGGER.info(String.valueOf(id));
        LOGGER.info(planet.toString());
    }
}

In the code above, we define a class named SolarSystem and log the name, id, and planets in the solar system to the console.

While an application is running, we can take the heap dump for further analysis using jmap. Also, we can take the heap dump programmatically:

static void dumpHeap(String filePath, boolean live) throws IOException {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
      server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
    mxBean.dumpHeap(filePath, live);
}

In the code above, we create MBeabServer and HotSpotDiagnosticMXBean objects to take the heap dump.

Next, let’s create a class named SolApp and add a method to instantiate the SolarSystem:

class SolApp {

    static void solarSystem() throws IOException {
        List<String> planet = new ArrayList<>();
        planet.add("Mercury");
        planet.add("Mars");
        planet.add("Earth");
        planet.add("Venus");
        SolarSystem solarSystem = new SolarSystem(1, "Sol System", planet);
        solarSystem.logSolarSystem();

        HeapDump.dumpHeap("solarSystem.hprof", true);
    }
}

Here, we instantiate the SolarSystem class with some planets and programmatically take the heap dump for profiling. The solarSystem.hprof file is dumped into the project root directory after execution.

Furthermore, let’s create a Heap object to load the heap dump:

Heap heap = HeapFactory.createHeap(new File("solarSystem.hprof"));

In the code above, we prepare the dump file for profiling. We can now invoke various methods on the Heap object for further analysis.

With a heap dump in hand, we can perform several analyses, such as understanding the memory usage of classes, detecting potential data leaks, and optimizing code performance based on the findings.

4. Heap Summary

Let’s start by getting a brief overview of the heap:

static void heapDumpSummary() {
    HeapSummary summary = heap.getSummary();
    LOGGER.info("Total instances: " + summary.getTotalLiveInstances());
    LOGGER.info("Total bytes: " + summary.getTotalLiveBytes());
    LOGGER.info("Time: " + summary.getTime());
    LOGGER.info("GC Roots: " + heap.getGCRoots().size());
    LOGGER.info("Total classes: " + heap.getAllClasses().size());
}

In the code above, we create a HeapSummary object and invoke various methods on it to examine the dump file.

Here’s the log output:

INFO com.baeldung.netbeanprofiler.SolApp -- Total instances: 79893
INFO com.baeldung.netbeanprofiler.SolApp -- Total bytes: 6235526
INFO com.baeldung.netbeanprofiler.SolApp -- Time: 1724568603079
INFO com.baeldung.netbeanprofiler.SolApp -- GC Roots: 2612
INFO com.baeldung.netbeanprofiler.SolApp -- Total classes: 3207

The result shows that 79893 live objects were active when the heap dump was collected. These live instances occupy approximately 6 MiB, with a total of 3207 classes whose instances account for the 79893 live objects.

The GC roots count is 2612 at the time of the dump.

5. Class Histogram

After getting an overview of our heap dump, let’s examine the classes and the number of instances used in the application.

First, let’s create an object to get all classes in the sample application:

List<JavaClass> unmodifiableClasses = heap.getAllClasses();

Next, let’s create a List object to store the classes for sorting:

List<JavaClass> classes = new ArrayList<>(unmodifiableClasses);
classes.sort((c1, c2) -> Long.compare(c2.getInstancesCount(), c1.getInstancesCount()));

Then, let’s loop through the JavaClass object:

for (int i = 0; i < Math.min(5, classes.size()); i++) {
    JavaClass javaClass = classes.get(i);
    LOGGER.info("  " + javaClass.getName());
    LOGGER.info("    Instances: " + javaClass.getInstancesCount());
    LOGGER.info("    Total size: " + javaClass.getAllInstancesSize() + " bytes");
}

In the code above, we invoke the getName()getInstancesCount(), and getAllInstancesSize() methods on javaClass to get the class name, the total number of instances created, and the total size of the instances respectively.

Here’s the console output:

INFO com.baeldung.netbeanprofiler.SolApp --   byte[]
INFO com.baeldung.netbeanprofiler.SolApp --     Instances: 18996
INFO com.baeldung.netbeanprofiler.SolApp --     Total size: 2714375 bytes
INFO com.baeldung.netbeanprofiler.SolApp --   java.lang.String
INFO com.baeldung.netbeanprofiler.SolApp --     Instances: 18014
INFO com.baeldung.netbeanprofiler.SolApp --     Total size: 540420 bytes
INFO com.baeldung.netbeanprofiler.SolApp --   java.util.concurrent.ConcurrentHashMap$Node
INFO com.baeldung.netbeanprofiler.SolApp --     Instances: 5522
INFO com.baeldung.netbeanprofiler.SolApp --     Total size: 242968 bytes

The result above shows the byte[] and String classes have the highest number of instances, with 18996 and 18014 instances respectively. This is expected because our SolarSystem class relies on String object underhood.

6. Profiling SolarSystem Object

Furthermore, let’s examine the SolarSystem class and investigate the size and count of its instances.

6.1. Total Size and Instances Count

First, let’s find the size and total instance count of the SolarSystem class:

static void solarSystemSummary() {
    JavaClass solarSystemClass = heap.getJavaClassByName("com.baeldung.netbeanprofiler.galaxy.SolarSystem");
    List<Instance> instances = solarSystemClass.getInstances();
    long totalSize = 0;
    long instancesNumber = solarSystemClass.getInstancesCount();
    for (Instance instance : instances) {
        totalSize += instance.getSize();
    }
    LOGGER.info("Total SolarSystem instances: " + instancesNumber);
    LOGGER.info("Total memory used by SolarSystem instances: " + totalSize);
}

Here, we create a JavaClass object and invoke the getJavaClassByName() method on the heap instance. Next, we get the instances of the class and log the number of instances and their size to the console:

INFO com.baeldung.netbeanprofiler.SolApp - Total SolarSystem instances: 1
INFO com.baeldung.netbeanprofiler.SolApp - Total memory used by SolarSystem instances: 36

From the console output, the SolarSystem instance was created once using 36 bytes. This matches the number of instances created in the example code, indicating the SolarSystem object is instantiated as expected.

6.2. Field Details

Furthermore, we can dig deep into a selected class to investigate its fields:

static void logFieldDetails() {
    JavaClass solarSystemClass = heap.getJavaClassByName("com.baeldung.netbeanprofiler.galaxy.SolarSystem");

    List<Field> fields = solarSystemClass.getFields();
    for (Field field : fields) {
        LOGGER.info("Field: " + field.getName());
        LOGGER.info("Type: " + field.getType().getName());
    }
}

In the code above, we select the SolarSystem class and get all its instances. Then we create a collection Field object and iterate through the collection. Finally, we log the name and type of the field to the console.

7. Exploring GC Roots

The GC roots provide a clear picture of the garbage collector’s behavior. Any objects being referenced directly or indirectly by GC roots won’t be garbage collected. It shows the object is still alive and not ready to be cleaned.

Let’s invoke the getGCRoots() method on the heap object to collect all the GC roots:

Collection<GCRoot> gcRoots = heap.getGCRoots();

In the code above, we invoke the getGCRoots() method on the heap instance to get a collection of GC roots.

Next, let’s create a variable to store the count of different GC roots:

int threadObj = 0, jniGlobal = 0, jniLocal = 0, javaFrame = 0, other = 0;

Then, let’s loop through the GC roots and count the number of Thread objects, Java Native Interface (JNI) Global and Local objects, and Java Frame:

for (GCRoot gcRoot : gcRoots) {
    Instance instance = gcRoot.getInstance();
    String kind = gcRoot.getKind();

    switch (kind) {
        case THREAD_OBJECT:
            threadObj++;
            break;
        case JNI_GLOBAL:
            jniGlobal++;
            break;
        case JNI_LOCAL:
            jniLocal++;
            break;
        case JAVA_FRAME:
            javaFrame++;
            break;
        default:
            other++;
    }
}

Here, we iterate over the GC roots and count the number of Thread objects, Java Frames, JNI Global References, JNI Local References, and others.

Thread objects are active threads at the time the heap dump was taken. Objects referenced by it are considered live and won’t be garbage collected. Java Frames represent object references in the JVM stack frame. It holds the local variables and method invocation details.

Also, the JNI allows Java code to interact with native code such as C or C++. Local references are valid within the scope of the native method that created them while global references retain a reference to a Java object beyond the scope of a single native method call.

Finally, let’s log the details to the console:

LOGGER.info("\nGC Root Summary:");
LOGGER.info("  Thread Objects: " + threadObj);
LOGGER.info("  JNI Global References: " + jniGlobal);
LOGGER.info("  JNI Local References: " + jniLocal);
LOGGER.info("  Java Frames: " + javaFrame);
LOGGER.info("  Other: " + other);

Here’s the result:

INFO com.baeldung.netbeanprofiler.SolApp --   Thread Objects: 8
INFO com.baeldung.netbeanprofiler.SolApp --   JNI Global References: 122
INFO com.baeldung.netbeanprofiler.SolApp --   JNI Local References: 1
INFO com.baeldung.netbeanprofiler.SolApp --   Java Frames: 481
INFO com.baeldung.netbeanprofiler.SolApp --   Other: 2000

From the result above, 8 Thread objects are still alive and the Java Frame count is 481 count.

8. Conclusion

In this article, we learned the basic profiling feature of NetBeans Profiler API by taking a heap dump programmatically and further analyzing it. Additionally, we saw how to get the heap summary and single out a class for profiling.

As always, the source code for the examples is available over on GitHub.