Eclipse memory analyzer java heap space

Eclipse Memory Analyzer (MAT) — Tutorial

The Eclipse Memory Analyser Tooling (MAT) is a set of plug-ins for the Eclipse IDE which provides tools to analyze heap dumps from Java application and to identify memory problems in the application. This helps the developer to find memory leaks and high memory consumption issues.

It visualizes the references to objects based on Java heap dumps and provides tools to identify potential memory leaks.

1.2. Using heap dumps to get a snapshot of the memory of an application

A heap dump is a snapshot of the complete Java object graph on a Java application at a certain point in time. It is stored in a binary format called HPROF.

It includes all objects, fields, primitive types and object references.

2. Installation

Install Eclipse MAT via the Help Install New Software…​ menu entry. Select the update site of your release from the drop-down box and once its content is downloaded, select General Purpose Tools and its sub-entries Memory Analyzer and Memory Analyzer(Charts).

Installation of MAT

3. Creating heap dumps for Java programs

It is possible to instruct the JVM to create automatically a heap dump in case that it runs out of memory, i.e. in case of a OutOfMemoryError error. To instruct the JVM to create a heap dump in such a situation, start your Java application with the -XX:+HeapDumpOnOutOfMemoryError option.

Use the File New Other…​ Other Heap Dump menu entry to open a dialog to select for which process you want to acquire a memory dump.

Creating a heap dump

Select the process for a heap dump in the following dialog and press the Finish button.

Alternatively you can also interactively create a heap dump via Eclipse. For this, open the Memory Analysis perspective via Perspective Open Perspective Other…​ .

Opening the MAT perspective

If you trigger the creation of the heap manually the JVM performs sa garbage collector run before it writes the heap dump.

4. Use the Eclipse Memory Analyzer

4.1. Reviewing a heap dump

After a new heap dump with the .hprof ending has been created, you can open it via a double-click in Eclipse. If you used MAT to create the heap dump, it should be opened automatically.

Читайте также:  What is css slicing

You may need to refresh your project (F5 on the project). Double-click the file and select the Leak Suspects Report.

Opening a leak report

The overview page allows you to start the analysis of the heap dump. The dominator tree gives quickly an overview of the used objects.

Opening the dominator tree

In the dominator tree you see the references which are hold.

MAT dominator tree

To find which element is holding the reference to this object, select the entry and select Find shortest path to GC root from the context menu.

4.2. Analyzing Android heap dumps with Eclipse

Android allows to create heap dumps of an application’s heap. This heap dump is stored in a binary format called HPROF. To create a heap dump use the Dump HPROF file button in the DDMS Perspective.

The Android heap dump format is similar to the Java heap dump format but not exactly the same. Eclipse MAT can work directly with the Android heap dump format.

5. Example

5.1. Create Project

Create the Java project called com.vogella.mat.first and the com.vogella.mat.first package. Create the following class.

package com.vogella.mat.first; import java.util.ArrayList; import java.util.List; public class Main  /** * @param args */ public static void main(String[] args)  ListString> list = new ArrayListString>(); while (12) list.add("OutOfMemoryError soon"); > > >

5.2. Create heap dump and analysis

In Eclipse add the -XX:+HeapDumpOnOutOfMemoryError to the runtime configuration.

Run the project. It crashes and writes an heap dump.

Open the heap dump in MAT and get familiar with using the MAT tooling.

6. jconsole

You can also interactively create a heap dumps via the jconsole, a tool which is included in the JDK. Type jconsole in the command line to start it.

To allow a Java program the access of jconsole use the -Dcom.sun.management.jmxremote start option.

Use them MBeans | com.sun.management | HotSpotDiagnostics | Operations |DumpHeap .

More info can be found in JConsole and JConsole Tutorial.

Источник

Eclipse Memory Analyzer – Java heap space Error when Opening an hprof

Interesting thing today; so in my adventures in running a diagnostic for why Java crashed; I got… a Java Crash on my computer when trying to open the crash dump! Okay not really but still interesting.

To analyze a hprof crash for why Java crashes; you can use a tool such as the Eclipse Memory Analyzer. This Open Source Project is a great tool and item to start with for analyzing crash dumps

Unfortunately after getting the program and opening the crash file which I was hoping to analyze my computer encountered the error:

2017-10-17_0928.png

'Parsing heap dump from 'C:\Users\stenbm2\Downloads\java_pid17404.hprof" has encountered a problem. An internal error occurred during: "Parsing heap dump from 'C:\Users\stenbm2\Downloads\java_pid17404.hprof'".

This most certainly cannot be! But we can always find more errors; so let’s “follow the logs”!

2017-10-17_0938.png

And we then find the errors:

2017-10-17_0939.png

eclipse.buildId=unknowneclipse.buildId=unknownjava.version=1.8.0_121java.vendor=Oracle CorporationBootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_USCommand-line arguments: -os win32 -ws win32 -arch x86_64 org.eclipse.core.jobsErrorTue Oct 17 09:28:00 EDT 2017An internal error occurred during: "Parsing heap dump from 'C:\Users\stenbm2\Downloads\java_pid17404.hprof'". java.lang.OutOfMemoryError: Java heap space at org.eclipse.mat.parser.index.IndexWriter.copyOf(IndexWriter.java:2013) at org.eclipse.mat.parser.index.IndexWriter$Identifier.add(IndexWriter.java:93) at org.eclipse.mat.hprof.HprofParserHandlerImpl.reportInstance(HprofParserHandlerImpl.java:588) at org.eclipse.mat.hprof.Pass1Parser.readInstanceDump(Pass1Parser.java:546) at org.eclipse.mat.hprof.Pass1Parser.readDumpSegments(Pass1Parser.java:360) at org.eclipse.mat.hprof.Pass1Parser.read(Pass1Parser.java:175) at org.eclipse.mat.hprof.HprofIndexBuilder.fill(HprofIndexBuilder.java:80) at org.eclipse.mat.parser.internal.SnapshotFactoryImpl.parse(SnapshotFactoryImpl.java:222) at org.eclipse.mat.parser.internal.SnapshotFactoryImpl.openSnapshot(SnapshotFactoryImpl.java:126) at org.eclipse.mat.snapshot.SnapshotFactory.openSnapshot(SnapshotFactory.java:145) at org.eclipse.mat.ui.snapshot.ParseHeapDumpJob.run(ParseHeapDumpJob.java:83) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

2017-10-17_0940.png

eclipse.buildId=unknown java.version=1.8.0_121 java.vendor=Oracle Corporation BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86_64 org.eclipse.mat.ui Info Tue Oct 17 09:27:44 EDT 2017 Detected compressed references, because with uncompressed 64-bit references the array at 0x7801192b8 would overlap the array at 0x780117210

And from the first error the primary code: java.lang.OutOfMemoryError: Java heap space

Egads! So thus the program to analyze Java Heap Crashes; crashed due to a Java Heap Space Error.

Well for Java Heap Space errors this can be corrected by checking the configuration for the impacted program/system. In this case, your installation folder should have the MemoryAnalyzer.ini file for the Java configuration.

2017-10-17_1346.png

From there; I was able to find the below information:

-startup plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.300.v20150602-1417 -vmargs -Xmx1024m

So to start; we can find the above has the xmx configuration (one of the more popular configuration references for Java); which is for the MaxHeapSize for Java. In this case the -Xmx1024m indicates that the system allocates approximately 1 GB of Memory for the Maximum Heap Size. Additionally:

-> This is for the Initial Heap Size. This would be initial value used and in general case is the amount that will usually grow from this size.

-> This is for the Maximum Heap Size that is allowed. If insufficient; Java can crash with the OutOfMemoryError we saw earlier.

While this is a tricky topic; it isn’t advisable to just increase the Java Heap Value on systems such as production without understanding the cause. In this case, it’s on my personal laptop and the HPROF file I was trying to reach was approximately 3.9 GB so I increased the value to 2 GB in the ini file and then relaunched (from 1024 to 2048m). However, your results may vary -> as my laptop had 8 GB of RAM.

To Do List -> More advanced topics on Java and memory allocation as this can be explained in greater detail to help confirm troubleshooting/reviews for possible/probable causes of crashes/unstable memory handling and what can be done to correct the crash.

Источник

Диагностика утечек памяти в Java

В данной заметке я хочу показать каким образом можно определять и устранять утечки памяти в Java на примере из моей повседневной работы. Мы не будем здесь рассматривать возможные причины появления утечек, об этом будет отдельная статья, так как тема достаточно обширная. Стоит заметить, что речь пойдет о диагностике именно Heap Memory, об утечках в других областях памяти будет отдельная статья.

Инструменты

Для успешной диагностики нам понадобятся два инструмента: Java Mission Control (jmc) и Eclipse Memory Analyzer. Вобщем-то можно обойтись только Memory Analyzer, но с JMC картина будет более полной.

Анализ использования памяти

Прежде всего, нужно запустить приложение со следующими флагами JVM:
-XX:+UnlockCommercialFeatures
-XX:+FlightRecorder

Не используйте эти опции на production системе без приобретения специальной лицензии Oracle!

Эти опции позволят запустить Flight Recorder – утилита, которая поможет собрать информацию об использовании памяти (и много другой важной информации) во время выполнения программы. Я не буду описывать здесь как запустить Flight Recorder, эта информация легко гуглится. В моем случае было достаточно запустить FR на 10-11 минут.

Рассмотрим следующий рисунок, на котором показана классическая «пила» памяти, а так же важный сигнал, что что-то не так с использованием памяти:

Запись Fight recorder

Можно увидеть, что после каждого цикла очистки памяти, heap все больше заполняется, я выделил это желтым треугольником. «Пила» все время как бы ползет вверх. Это значит, что какие-то объекты не достижимы для очистки и накапливаются в old space, что со временем приведет к переполнению этой области памяти.

Выявление утечки

Следующим шагом нужно выявить, что именно не доступно для очистки и в этом нам поможет Memory Analyzer. Прежде всего, нужно загрузить в программу heap dump работающего приложения с предполагаемой утечкой памяти. Это можно сделать с помощью «File → Acquire Heap Dump». После загрузки в диалоге «Getting Started Wizard» выбрать «Leak Suspects Report» после этого откроется краткий обзор возможных утечек памяти:

Leak suspects report

Если вернуться на вкладку «Overview» и выбрать «Dominator Tree», то можно увидеть более подробную картину:

Overview

Denominator tree

Дерево показывает структуру «тяжелого» объекта, а так же размер его полей (по типу). Можно видеть, что одно из полей объекта MasterTenant занимает более 45% памяти.

Устранение утечки

Имея результат анализа из предыдущего пункта, следующим шагом идет устранение накапливания объектом памяти. Тут все сильно зависит от конкретного кода. Общая рекоменация – нужно найти и проанализировать все места, где происходит инициализация или изменение соответствующего поля или полей, чтобы понять механизм накапливания памяти. В моем случае в коллекцию постоянно добавлялись записи из множества (около 150) потоков при определенных условиях.

После находжения и устранения утечки, не лишним будет пройти все шаги снова, проанализировать память и отчет Memory Analyzer, чтобы убедиться что фикс помог.

Источник

Оцените статью