Java check process memory

How to get free memory info from Java

The Free_Memory I got was : 900, but it is way off, when Free_Memory goes down to around 600, my program ran out of memory and generated heap overflow message. So I looked at the => Windows Task Manager : Performance : Physical Memory : Free, it’s down to 1, 2 or 0, which is a more accurate reflection of my memory situation, and according to it, my Total Memory is : 4089, which is correct, while Java’s Total_Memory=992 is incorrect. So, my question now is : In my Java program how to get the memory usage numbers reflected in the Windows Task Manager : Performance : Physical Memory ? I need to depend on those numbers.

Then help him understand what they ARE reporting. Comments like that are so f’in useless. Runtime.freeMemory reports the amount of memory available to the Java VM, not the system itself.

Sorry, Chris Vann. I’d already posted an answer and deleted it, then I thought at least part of it might be helpful so I posted a comment. But I’m not sure why he’s running out of memory when freeMemory() is still reporting 600 MB free.

2 Answers 2

The JVM doesn’t allow Java to consume all available system memory. Instead the JVM grabs a fixed chunk and allocates all of your objects within that chunk. If this area fills up, you’re out of memory! There are commandline options to alternate the max/initial memory usage of the JVM.

The more important issue is that you should not be relying on tracking free/max memory. What are you doing that relies on tracking memory?

Try 64bit if you need more memory than 1.5GB

If you’re trying to track memory running out then consider figuring our WHY your program does this and if it can be prevented through different algorithms or better management of objects. When the memory reaches zero what do you expect to do? Popup a dialog and tell the user they’re screwed and exit the program? I can understand a grateful shutdown but warning the user to run with a large -Xmx is not going to cut it.

Читайте также:  Css точка или без

Источник

Java check process memory

Many commands can check the memory utilization of JAVA processes, for example, pmap, ps, jmap, jstat.
What are the differences?
Before we move forward, we need to know heap and stack.
Simply saying, heap space contains 1 Eden space , 2 young generations and 1 old generation; stack space is the permanent generation.
Here is one great article about .

Take «ResourceManager» process for example:

[root@admin ~]# jps 2304 ResourceManager

1. ps and pmap can show total reserved memory from OS.

[root@admin ~]# ps auwx|egrep "MEM|2304"|grep -v grep USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND yarn 2304 0.8 2.3 826132 192484 ? Sl 08:54 4:02 /usr/java/jdk1.7.0_45-cloudera/bin/java -Dproc_resourcemanager
[root@admin ~]# pmap -x 2304 2304: /usr/java/jdk1.7.0_45-cloudera/bin/java -Dproc_resourcemanager Address Kbytes RSS Dirty Mode Mapping 0000000000400000 4 4 0 r-x-- java 0000000000600000 4 4 4 rw--- java (. ) ---------------- ------ ------ ------ total kB 826132 192404 172608

«ps auwx|grep » shows totally 800MB+ virtual memory(including 190MB physical memory) are reserved.
«pmap -x » shows the same.
Because reserved memory includes shared memory also, it is hard for you to know how much heap memory are used and allocated.

2. jmap and jstat can show used space of heap&stack.

[root@admin ~]#jmap -heap 2304|egrep ":|used color: blue;">New Generation (Eden + 1 Survivor Space): used = 44627176 (42.559791564941406MB) Eden Space: used = 44264776 (42.21417999267578MB) From Space: used = 362400 (0.345611572265625MB) To Space: used = 0 (0.0MB) concurrent mark-sweep generation: used = 8410104 (8.020500183105469MB) Perm Generation: used = 32389728 (30.889251708984375MB)
[root@admin ~]# jstat -gc 2304 S0C S1C S0U S1U EC EU OC OU PC PU YGC YGCT FGC FGCT GCT 8064.0 8064.0 353.9 0.0 65088.0 43227.3 163520.0 8213.0 31808.0 31630.6 32 0.254 0 0.000 0.254

To understand «jstat» output, please check article firstly.
Here we can see the mapping relationship between outputs from jmap and jstat.

New Generation(used memory) = S0U+S1U+EU
concurrent mark-sweep generation(used memory) = OU
Perm Generation(used memory)=PU.

So the total used heap+stack memory size matches between «jmap» and «jstat»:

>>> (44627176+8410104+32389728)/1024.0/1024.0 81.46954345703125 >>> (353.9+0.0+43227.3+8213.0+31630.6)/1024.0 81.469531250000003

3. jmap -histo can show top heap memory objects

[root@admin ~]# jmap -histo -F 2304 |more Attaching to process ID 2304, please wait. Debugger attached successfully. Server compiler detected. JVM version is 24.45-b08 Iterating over heap. This may take a while. Object Histogram: num #instances #bytes Class description -------------------------------------------------------------------------- 1: 59262 7949504 * ConstMethodKlass 2: 59262 7595200 * MethodKlass (. ) 2721: 1 16 com.sun.research.ws.wadl.Doc$JaxbAccessorF_title Total : 440785 44864280

Источник

Читайте также:  Java preparedstatement в postgresql

Java check process memory

Many commands can check the memory utilization of JAVA processes, for example, pmap, ps, jmap, jstat.
What are the differences?
Before we move forward, we need to know heap and stack.
Simply saying, heap space contains 1 Eden space , 2 young generations and 1 old generation; stack space is the permanent generation.
Here is one great article about .

Take «ResourceManager» process for example:

[root@admin ~]# jps 2304 ResourceManager

1. ps and pmap can show total reserved memory from OS.

[root@admin ~]# ps auwx|egrep "MEM|2304"|grep -v grep USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND yarn 2304 0.8 2.3 826132 192484 ? Sl 08:54 4:02 /usr/java/jdk1.7.0_45-cloudera/bin/java -Dproc_resourcemanager
[root@admin ~]# pmap -x 2304 2304: /usr/java/jdk1.7.0_45-cloudera/bin/java -Dproc_resourcemanager Address Kbytes RSS Dirty Mode Mapping 0000000000400000 4 4 0 r-x-- java 0000000000600000 4 4 4 rw--- java (. ) ---------------- ------ ------ ------ total kB 826132 192404 172608

«ps auwx|grep » shows totally 800MB+ virtual memory(including 190MB physical memory) are reserved.
«pmap -x » shows the same.
Because reserved memory includes shared memory also, it is hard for you to know how much heap memory are used and allocated.

2. jmap and jstat can show used space of heap&stack.

[root@admin ~]#jmap -heap 2304|egrep ":|used color: blue;">New Generation (Eden + 1 Survivor Space): used = 44627176 (42.559791564941406MB) Eden Space: used = 44264776 (42.21417999267578MB) From Space: used = 362400 (0.345611572265625MB) To Space: used = 0 (0.0MB) concurrent mark-sweep generation: used = 8410104 (8.020500183105469MB) Perm Generation: used = 32389728 (30.889251708984375MB)
[root@admin ~]# jstat -gc 2304 S0C S1C S0U S1U EC EU OC OU PC PU YGC YGCT FGC FGCT GCT 8064.0 8064.0 353.9 0.0 65088.0 43227.3 163520.0 8213.0 31808.0 31630.6 32 0.254 0 0.000 0.254

To understand «jstat» output, please check article firstly.
Here we can see the mapping relationship between outputs from jmap and jstat.

New Generation(used memory) = S0U+S1U+EU
concurrent mark-sweep generation(used memory) = OU
Perm Generation(used memory)=PU.

So the total used heap+stack memory size matches between «jmap» and «jstat»:

>>> (44627176+8410104+32389728)/1024.0/1024.0 81.46954345703125 >>> (353.9+0.0+43227.3+8213.0+31630.6)/1024.0 81.469531250000003

3. jmap -histo can show top heap memory objects

[root@admin ~]# jmap -histo -F 2304 |more Attaching to process ID 2304, please wait. Debugger attached successfully. Server compiler detected. JVM version is 24.45-b08 Iterating over heap. This may take a while. Object Histogram: num #instances #bytes Class description -------------------------------------------------------------------------- 1: 59262 7949504 * ConstMethodKlass 2: 59262 7595200 * MethodKlass (. ) 2721: 1 16 com.sun.research.ws.wadl.Doc$JaxbAccessorF_title Total : 440785 44864280

Источник

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

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

Читайте также:  How to point to css

Инструменты

Для успешной диагностики нам понадобятся два инструмента: 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, чтобы убедиться что фикс помог.

Источник

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