简体   繁体   中英

Java,How do I find out which class or method USES a lot of memory?

在此处输入图片说明

This is a one-day memory curve for my Java project.How do I find out which class or method USES a lot of memory?

You need a tool that can do JVM allocation profiling .

Java Flight Recorder (JFR) can help you with low overhead allocation profiling ( 1 , 2 — docs for older versions, the UI looks quite different now, but "Allocations" and "TLAB" are still the words used to find stuff). Make sure that allocation profiling is enabled in the settings you use. It's a commercial feature until OpenJDK 11. They say some other tools can do it with low overhead these days too (eg async-profiler ).

If you don't care about your app becoming unusably slow and are on JDK < 11(?), VisualVM used to be able to show you stack traces of allocations. I can't find it in the latest version (1.4.2 as of now), but can find it in JVisualVM shipped with my Oracle JDK 8-something. "Profiler" > check "Settings" > "Memory Settings" > check "Record allocation stack traces". Start profiling, wait, wait, wait, identify the biggest allocations, right-click, "Take Snapshot and Show Allocation Stack Traces". It looks like YourKit does basically the same , as well as JProfiler (they call it "allocation recording"). Again: slows down the application a lot, so don't use it in prod.

You have take a heap dump periodically and analyse these with tools like MAT- Memory Analyzer Tool ( https://www.eclipse.org/mat/ ). The tool provides the which Object / Class occupying more memory and from which thread it is created etc.

How to find from which thread particular object is created?

  1. In the MAT, click on the Histogram - It will show the list of classes available in the dump. To demonstrate, let me filter out the class java.lang.String only

在此处输入图片说明

  1. Right click any class name , in the popup-window choose List Objects ---> with outgoing references

在此处输入图片说明

  1. Above Step list out all the instances of the selected class. Right click any one of the class name and from the pop up choose Merge Shortest Paths to GC Roots ---> with all references

在此处输入图片说明

  1. After the above step, you can view the From which Thread class particular object is created.

在此处输入图片说明

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