Русские Блоги
Итак, обычно есть две причины этой аномалии:
1. В программе есть бесконечный цикл.
2. Программа занимает слишком много памяти, что превышает максимальное значение, установленное кучей JVM.
В первом случае вам необходимо самостоятельно проверить программный код, поэтому я не буду здесь говорить больше.
Во втором случае мы вручную расширяем настройки параметров кучи JVM. Настройка кучи JVM относится к настройке пространства памяти, которое JVM может выделить и использовать во время выполнения программы java. Когда JVM запускается, куча JVM автоматически устанавливает значение размера кучи. Обычно значение по умолчанию для начального пространства (например, -Xms) составляет 1/64 физической памяти, а максимальное пространство составляет 1/4 физической памяти. Его можно установить с помощью таких параметров, как -Xmn -Xms -Xmx, предоставляемых JVM. Вот объяснение значения каждого параметра:
-Xms: начальное значение
-Xmx: максимум
-Xmn: минимальное значение
Размер кучи не должен быть слишком маленьким или слишком большим. Если параметр слишком мал, скорость отклика программы будет ниже, потому что сборщик мусора занимает больше времени, а приложение выделяет меньше времени на выполнение. Слишком большой размер также приведет к потере места и повлияет на нормальную работу других программ. Размер кучи не должен превышать 80% доступной физической памяти. Рекомендуется установить одинаковые параметры -Xms и -Xmx, а -Xmn составляет 1/4 значения -Xmx.
Основные методы настройки следующие:
1. Этот параметр добавляется при выполнении файла класса JAVA, где className — это имя класса, который необходимо выполнить. (Включая имя пакета) Например: java -Xms32m -Xmx800m className Это не только решает проблему, но и скорость выполнения намного выше, чем когда она не установлена. Если это тест разработки, вы также можете установить его прямо в eclipse. Введите -Xms32m -Xmx800m в аргументы виртуальной машины в Eclipse -> run -arguments.
2. Вы можете изменить системные переменные среды в Windows и добавить JAVA_OPTS = -Xms64m -Xmx512m.
3. Если вы используете tomcat под окнами, вы можете добавить в C: \ tomcat5.5.9 \ bin \ catalina.bat (конкретный путь зависит от местоположения вашего tomcat): установить JAVA_OPTS = -Xms64m -Xmx256m (размер зависит от вашей собственной памяти) Местоположение: rem Угадайте CATALINA_HOME, если не определено Добавьте соответствующее в этой строке.
4. Если это система Linux, добавьте набор JAVA_OPTS = ’- Xms64 -Xmx512’ перед
Поскольку программе необходимо прочитать около 10 Вт строк записей из данных для обработки, возникает ошибка типа java.lang.OutOfMemoryError: пространство кучи Java появляется при чтении 9 Вт.
Проверка в Интернете может быть причиной того, что параметр стека JAVA слишком мал.
Согласно ответам в Интернете, существует примерно два решения:
1. Задайте переменные среды.
set JAVA_OPTS= -Xms32m -Xmx512m
можно изменить в соответствии с объемом памяти вашего компьютера, но моя проверка этого метода не решила проблему. Это может быть где еще нужно установить.
2、java -Xms32m -Xmx800m className
— добавить этот параметр при выполнении файла класса JAVA, где className — это фактическое имя класса, который должен быть выполнен. (Включая название пакета)
Это решает проблему. И скорость выполнения намного выше, чем без настройки.
Если вы можете использовать Eclispe при тестировании, вам необходимо ввести параметр -Xms32m -Xmx800m в аргументы виртуальной машины в Eclipse -> run -arguments.
java.lang.OutOfMemoryError: Java heap space
Исключение возникает при использовании программы Java для запроса большого количества данных из базы данных:
java.lang.OutOfMemoryError: Java heap space
В JVM, если 98% времени используется для сборки мусора, а доступный размер кучи меньше 2%, будет выдано это сообщение об исключении.
Настройка кучи JVM относится к настройке пространства памяти, которое JVM может выделить и использовать во время выполнения программы java.
JVM автоматически установит значение размера кучи при запуске.Его начальное пространство (-Xms) составляет 1/64 физической памяти, а максимальное пространство (-Xmx) — 1/4 физической памяти. Его можно установить с помощью таких параметров, как -Xmn -Xms -Xmx, предоставляемых JVM.
Например: java -jar -Xmn16m -Xms64m -Xmx128m MyApp.jar
Если размер кучи установлен слишком маленьким, в дополнение к этим аномальным сообщениям вы обнаружите, что скорость отклика программы снижается. Сборщик мусора занимает больше времени, а приложение выделяет меньше времени на выполнение.
Размер кучи не должен превышать 80% доступной физической памяти.Обычно для параметров -Xms и -Xmx должны быть установлены одинаковые значения, а -Xmn составляет 1/4 значения -Xmx.
Параметры размера кучи -Xms -Xmn не должны превышать размер физической памяти. В противном случае появится сообщение «Ошибка при инициализации виртуальной машины. Не удалось зарезервировать достаточно места для кучи объектов».
==========================================================
После ночи напряженной работы я наконец завершил программу замены файлов для указанной строки, но поскольку я хочу заменить слишком много файлов html для общесайтовой программы, поэтому затмение всегда заканчивается в каталоге После сообщения об исключении java.lang.OutOfMemoryError: пространство кучи Java произошел сбой.
Я подумал, что слишком поздно перерабатывать из-за частых операций, поэтому я добавил Thread.sleep (1000) после каждого цикла и обнаружил, что он умрет в этом каталоге, поэтому я изменил 1000 на 5000 или умер там. Я думаю, что это может быть не так просто перерабатывать, возможно, JVM Sun просто не выпускает для этой ситуации.
Затем я добавил -Xmx256M к параметру запуска, на этот раз все было нормально.
Подумав об этом, я до сих пор мало что знаю о принципах сборки мусора, я проверил это в Интернете и нашел несколько хороших статей.
Также существуют: Управление кучей Java — сборка мусора. Следует отметить следующие моменты, которые могут использоваться в качестве рекомендаций при написании программ:
(1) Не пытайтесь предполагать время, когда происходит сборка мусора, причем все это неизвестно. Например, временный объект в методе становится бесполезным после вызова метода, и его память может быть освобождена в это время.
(2) Java предоставляет несколько классов, которые занимаются сборкой мусора, и предоставляет способ принудительного вызова функции сборки мусора System.gc (), но это также ненадежный метод. Java не гарантирует, что сборка мусора будет запускаться каждый раз при вызове этого метода. Она просто отправляет такой запрос в JVM. Неизвестно, выполняется ли сборка мусора на самом деле.
(3) Выберите подходящий вам сборщик мусора. Вообще говоря, если система не предъявляет особых требований к производительности, вы можете использовать параметры JVM по умолчанию. В противном случае вы можете рассмотреть возможность использования целевых сборщиков мусора.Например, инкрементные сборщики больше подходят для систем с высокими требованиями к работе в реальном времени. Система имеет более высокую конфигурацию и больше простаивающих ресурсов, вы можете рассмотреть возможность использования параллельного сборщика меток / разверток.
(4) Ключевая и сложная проблема — это утечки памяти. Хорошие навыки программирования и строгое отношение к программированию всегда являются самыми важными. Не позволяйте небольшой собственной ошибке вызвать большую дыру в памяти.
(5) Освободите ссылки на бесполезные объекты как можно скорее.
Когда большинство программистов используют временные переменные, они автоматически устанавливают для ссылочной переменной значение null после выхода из активной области (области), что означает, что сборщик мусора будет собирать объект. Вы должны обратить внимание на то, отслеживается ли объект, на который указывает ссылка, если да, удалите прослушиватель, а затем назначьте нулевое значение.
Другими словами, лучше контролировать операции частого обращения к памяти и освобождения памяти самостоятельно, но метод System.gc () может быть неприменим. Лучше использовать finalize для принудительного выполнения или написать свой собственный метод finalize.
Я обнаружил ошибку TOMCAT: java.lang.OutOfMemoryError: пространство кучи Java, поэтому я проверил информацию и нашел решение:
If Java runs out of memory, the following error occurs:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
Java heap size can be increased as follows:
java -Xms -Xmx
Defaults are:
java -Xms32m -Xmx128m
Если вы используете выигрыш
/tomcat/bin/catalina.bat плюс следующая команда:
set JAVA_OPTS=-Xms32m -Xmx256m
Если вы используете unix / linux
/tomcat/bin/catalina.sh плюс следующая команда:
JAVA_OPTS="-Xms32m -Xmx256m"
инструмент просмотра и анализа памяти jvm
В отрасли существует множество мощных инструментов для профилей Java, таких как Jporfiler и yourkit. Я не хочу говорить об этих платных вещах. Я хочу сказать, что сама java обеспечивает большой мониторинг памяти. Маленькие инструменты, перечисленные ниже инструменты — лишь небольшая часть. Все еще довольно интересно внимательно изучить инструменты jdk 🙂
1: вывод журнала gc
-verbose: gc и -XX: + PrintTenuringDistribution и т. д.
Код коллекции HTML-кода
Usage:
jmap -histo (to connect to running process and print histogram of java object heap
jmap -dump: (to connect to running process and dump java heap)
dump-options: format=b binary default file=
dump heap to
Example: jmap -dump:format=b,file=heap.bin
jmap -dump:file=c:\dump.txt 340
Обратите внимание, что 340 — это pid java-процесса моей машины. Размер выгруженного файла превышает 10 мегабайт, и я только что открыл tomcat и запустил очень простое приложение без какого-либо доступа. Его можно представить на большом и загруженном сервере. , Насколько большим должен быть файл дампа? Что вам нужно знать, так это то, что информация о файле дампа очень примитивна и определенно не подходит для просмотра людьми напрямую, а содержимое, отображаемое jmap -histo, слишком простое, например, оно только показывает, сколько памяти занимают определенные типы объектов и количество этих объектов. , Но нет более подробной информации, например, кто создал эти объекты. Итак, какая польза от файла дампа? Конечно полезно, потому что есть инструмент для анализа файла дампа памяти jvm.
6: анализатор памяти eclipse
S0 S1 E O P YGC YGCT FGC FGCT GCT
54.62 0.00 42.87 43.52 86.24 1792 5.093 33 7.670 12.763
S0 S1 E O P YGC YGCT FGC FGCT GCT
54.62 0.00 42.87 43.52 86.24 1792 5.093 33 7.670 12.763
S0: Зона susvivor0 нового поколения, коэффициент использования площадей 54 . 62%
S1: область susvivor1 нового поколения, коэффициент использования пространства составляет 0,00% (поскольку второй второстепенный сбор не был выполнен)
Java.lang.OutOfMemoryError: Java heap space on Elasticsearch in AWS
![]()
When you get this error, AWS instance get stuck, CPU usage goes high or Elasticsearch and other service which depends on Elasticsearch service may keep restarting.
In the situation you are running ELK stack on Docker swarm, You may run bunch of services on you Manager node including Elasticsearch container.
Java applications are only allowed to use a limited amount of memory. This limit is specified during application startup. To make things more complex, Java memory is separated into two different regions. These regions are called Heap space and Permgen (for Permanent Generation):
The size of those regions is set during the Java Virtual Machine (JVM) launch and can be customized by specifying JVM parameters -Xmx and -XX:MaxPermSize. If you do not explicitly set the sizes, platform-specific defaults will be used.
The java.lang.OutOfMemoryError: Java heap space error will be triggered when the application attempts to add more data into the heap space area, but there is not enough room for it.
Note that there might be plenty of physical memory available, but the java.lang.OutOfMemoryError: Java heap space error is thrown whenever the JVM reaches the heap size limit.
What is causing it?
There most common reason for the java.lang.OutOfMemoryError: Java heap space error is simple — you try to fit an XXL application into an S-sized Java heap space. That is — the application just requires more Java heap space than available to it to operate normally. Other causes for this OutOfMemoryError message are more complex and are caused by a programming error:
- Spikes in usage/data volume. The application was designed to handle a certain amount of users or a certain amount of data. When the number of users or the volume of data suddenly spikes and crosses that expected threshold, the operation which functioned normally before the spike ceases to operate and triggers the java.lang.OutOfMemoryError: Java heap space error.
- Memory leaks. A particular type of programming error will lead your application to constantly consume more memory. Every time the leaking functionality of the application is used it leaves some objects behind into the Java heap space. Over time the leaked objects consume all of the available Java heap space and trigger the already familiar java.lang.OutOfMemoryError: Java heap space error.
Solutions :
There are two solutions that I’m going to discuss.
1. Increase heap size
In this soultion there are two possible solutions,
1.1. Mount the file by changing Heap size from host to container
You can change Heap size of Elasticsearch from jvm.options file where it located inside the Elasticsearch container in this path :
so you need to mount this file from host to container.
step 1: create a file on your server as jvm.options.
step 2: Copy and paste following code into the file.
Note* : You can copy this content it from inside container where this file located in /usr/share/elasticsearch/config/jvm.options. To get inside container, do following way: docker exec -it <container_id> bash.
before Copy this content, make sure to increase size of -Xms & -Xmx more than current size.
After adding this file, change docker-compose.yml file and mount this file into container
1.2. Override Heap Size inside docker-compose.yml file by overriding ENV variables.
Most of the time current node may does not has enough memeory space to allocate on Elasticsearch. To avoid such a situation you may go to the second solution.
2. Transfer your container into another worker node or manager node:
Before you do it, make sure to choose a server which has plenty of memory space. To do that you have to add some lines into your docker-compose.yml file. By adding those line we force to run Elasticsearch container on worker node.
You can specify as manger or worker. Also , without adding manger or worker, you can add host name of you server.
This is expected to resolve any Elasticsearch stability issues due to java heap.
OutOfMemory Java Heap Space
From the diagram above, we can see that the heap is used to allocate memory to Objects and JRE classes.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs.
Heap Size
Java applications are only allowed to use a limited amount of memory.
Heap size is set during the JVM launch and can be modified by specifying JVM parameters -Xmx .
For example, in setenv.bat of tomcat,
If you do not explicitly set the sizes, platform-specific defaults will be used.
OutOfMemory — Java Heap Space
When the heap becomes full, garbage is collected.
During the garbage collection objects that are no longer used/referenced are cleared, thus making space for new objects.
Hence, if JVM cannot allocate an object because heap is out of memory, and no more memory could be made available by the garbage collector, then OutOfMemory is thrown.
Reasons
There are two main reasons to get this error:
poor programming cause memory leak — infinite loop, not clearing memory by closing resources etc
low heap size — java is running on less memory than required
Memory Leak
Garbage collection ( GC) is the process to remove unreferenced objects from the heap memory. However GC may not always give you 100% results. There might be some unused objects which GC cannot remove because some other object is still holding a reference to it. This concept is called as Memory Leak.
We can see in the below image that object X is holding the reference of object Y. Object Y has completed its task but cannot be garbage collected because of the unwanted reference.

How to solve
increase the heap size
find the root cause to memory leak in your programme and solve it
In most cases, #2 is what we should do. If there is memory leak in your code, only increase heap size cannot eliminate this error.
In order to find the memory leak in code, we need to :
Get the heap dump info
Analysise the heap dump
Get the heap dum info
manually collect
jmap is a JDK built in tool which can be used to create heap dump file by using the following command:
jmap -heap:live,format=b,file=/home/test.bin <pid>
<pid> is the process id of java.
It’s quite important to pass live option. If this option is passed, then only live objects in the memory are written into the heap dump file.
If this option is not passed, all the objects, even the ones which are ready to be garbage collected are printed in the heap dump file. It will increase the heap dump file size significantly as well as analysis tedious.
automatic collect
Alternatively, you can add -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=D:\heapdump.bin to tomcat CATALINA_OPTS config, such that tomcat will create heap dump file when it encounters OutOfMemory error.
Analysise the heap dump
The heap dump file can be parsed by jvisualvm (which is jdk built in tool) or eclipse memory analysis(it is available as a stand-alone application or as a plugin for Eclipse).
Eclipse Memory Analysis Tool
The MAT looks like next:

The top left button with circled by red pen is:Accquire heap dump from a locally running vm, its next button is:open heap dump
Shallow vs Retained Heap
Shallow heap is the memory consumed by one object. This object might be referencing to other objects in the heap memory. Retained heap is sum of memory of this object’s and all other referenced objects.
Any object X might be consuming small memory by itself but referencing too many other unused objects. If this object is alive, garbage collector will not be able to free these unused objects from memory. In this case object X becomes important to be garbage collected because it is keeping a large set of retained heap. User should find and debug the objects where shallow heap is low and retained heap is high.

Dominator tree
There is a OutOfMemory error — java heap space thrown, and its heap dump info looks like:

From the above screenshot, we can see that the biggest value of retained heap is about the jdbcresult, so the memory leak is caused by a sql query.
Right click this entry -> List Objects -> with outgoing references, we can see that:

The above screen shot tells us that this sql query has too many results, as a consequence, it cause the OutOfMemory error.
How to fix java.lang.OutOfMemoryError: Java heap space
If you get an OutOfMemoryError with the message “Java heap space” (not to be confused with message “PermGen space”), it simply means the JVM ran out of memory. When it occurs, you basically have 2 options:
Solution 1. Allow the JVM to use more memory
With the -Xmx JVM argument, you can set the heap size. For instance, you can allow the JVM to use 4 GB (4096 MB) of memory with the following command:
Solution 2. Improve or fix the application to reduce memory usage
In many cases, like in the case of a memory leak, that second option is the only good solution. A memory leak happens when the application creates more and more objects and never releases them. The garbage collector cannot collect those objects and the application will eventually run out of memory. At this point, the JVM will throw an OOM ( OutOfMemoryError ).
A memory leak can be very latent. For instance, the application might behave flawlessly during development and QA. However, it suddenly throws a OOM after several days in production at customer site. To solve that issue, you first need to find the root cause of it. The root cause can be very hard to find in development if the problem cannot be reproduced. Follow those steps to find the root cause of the OOM:
Step 1. Generate a heap dump on OutOfMemoryError
Start the application with the VM argument -XX:+HeapDumpOnOutOfMemoryError . This will tell the JVM to produce a heap dump when a OOM occurs:
Step 2. Reproduce the problem
Well, if you cannot reproduce the problem in dev, you may have to use the production environment. When you reproduce the problem and the application throws an OOM, it will generate a heap dump file.
Step 3. Investigate the issue using the heap dump file
Use VisualVM to read the heap dump file and diagnose the issue. VisualVM is a program located in JDK_HOME/bin/jvisualvm . The heap dump file has all information about the memory usage of the application. It allows you to navigate the heap and see which objects use the most memory and what references prevent the garbage collector from reclaiming the memory. Here is a screenshot of VisualVM with a heap dump loaded:

This will give you very strong hints and you will (hopefully) be able to find the root cause of the problem. The problem could be a cache that grows indefinitely, a list that keeps collecting business-specific data in memory, a huge request that tries to load almost all data from database in memory, etc.
Once you know the root cause of the problem, you can elaborate solutions to fix it. In case of a cache that grows indefinitely, a good solution could be to set a reasonable limit to that cache. In case of a query that tries to load almost all data from database in memory, you may have to change the way you manipulate data; you could even have to change the behavior of some functionalities of the application.
Manually triggering heap dump
If you do not want to wait for an OOM or if you just want to see what is in memory now, you can manually generate heap dump. Here 2 options to manually trigger a heap dump.
Option 1. Use VisualVM
Open VisualVM ( JDK_HOME/bin/jvisualvm ), right-click on the process on the left pane and select Heap Dump. That’s it.
Option 2. Use command line tools
If you do not have a graphical environment and can’t use vnc (VisualVM needs a graphical environment), use jps and jmap to generate the heap dump file. Those programs are also located in JDK_HOME/bin/ .
Finally copy the heap dump file (heap.bin) to your workstation and use VisualVM to read the heap dump: File -> Load…
Alternatively, you can also use jhat to read heap dump files.
Solution 3 (bonus). Call me
You can also contact my application development company and I can personally help you with those kind of issues