小能豆

How to identify the top 20 heap objects in Java?

javascript

I am working on a Java application that is experiencing some memory problems. I want to identify the top 20 objects in the heap so that I can see where the memory is being used. I need to calculate this programmatically at runtime with java.

The heap objects should give the object size, file name, class name, method name and the line number in that file.

Can someone please help me identify the top 20 heap objects in Java?

I took the java heap dump and try to parse the file. But it didn’t work. Because i need to calculate the top 20 java heap objects details for every minute.

Is there any java open source available to calculate the java application heap usages at runtime without causing any overhead to the application.


阅读 86

收藏
2023-11-21

共1个答案

小能豆

Calculating the top heap objects at runtime is a complex task and typically involves profiling tools. One popular and widely used tool for Java heap analysis is Java VisualVM, which is bundled with the JDK.

Here’s a general approach to analyze the heap at runtime:

  1. Java VisualVM:

  2. Run your Java application.

  3. Open Java VisualVM (located in the bin directory of your JDK installation).
  4. Connect Java VisualVM to your running application.
  5. Navigate to the “Profiler” tab.
  6. Take a heap dump by clicking the “Heap Dump” button.

This allows you to analyze the heap dump in Java VisualVM and identify memory-hungry objects.

  1. JVisualVM API:

  2. You can also use the VisualVM API to programmatically interact with Java VisualVM. This API allows you to take heap dumps, perform memory analysis, and extract information about the heap.

  3. More information about the VisualVM API can be found here: VisualVM Developer Documentation

  4. Heap Profiling Libraries:

  5. There are also some libraries that provide heap profiling capabilities for Java applications. One example is the async-profiler library, which can be used to profile your application and generate flame graphs.

It’s important to note that performing heap analysis at runtime can introduce overhead, and in a production environment, it’s usually recommended to use profiling tools judiciously and only when needed.

If you want to automate the process of taking heap dumps and analyzing them, you might consider using a tool like Heapster, which is a command-line utility for analyzing Java heap dumps. It provides various reports, including top objects, retained sizes, and more.

Remember to be cautious about introducing profiling tools into a production environment, as they may impact the performance of your application. Always perform such activities in a controlled environment or during maintenance windows.

2023-11-21