简体   繁体   中英

How to determine where an object was instantiated in VisualVM Heap Dump

I have a bug in my program that is generating a lot of String instances (7000+ in Heap according to VisualVM ). I am trying to isolate which class is responsible for this so I can understand why it is happening.

The following is an example of the heap dump for String :

在此输入图像描述

How do I figure out which class is responsible for generating each of the String ? I am working with about 40 classes together so I would like to be able to identify the culprit class through VisualVM if possible.

You should have a look at this Q/A: How to view memory allocation stacktrace in Java VisualVM - a heap profile, which is a "memory allocation stacktrace" is what you want.

Here is a nice tutorial : Analyzing Memory Leak in Java Applications using VisualVM .

In general, there is several ways howto diagnose this problem, using a Java profiler:

  • use CPU profiling , the best in a instrumentation mode, this will record all method invocations, look at String.<init> - this will show you all the possible methods that execute new String() . The best tools are eg jProfiler, Java Mission Control, where you can easily identify all the callers of the String.<init> . The same applies for VisualVM. I think using CPU profiling is the most straightforward way of idenifying where in the code the new String occurs the most.

  • collect a heap dump in MAT , and analyze that, this will allow you to traverse the heap, you will again search for String finding all the references to a String object.

  • use Heap profiling option of a Java profiler (eg VisualVM), is similar to collecting a heap dump, only this heap profiling is usually collected online. So just enable heap profiling in VisualVM and follow the references from the String instances (ie find objects referencing String).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM