Jenkins java lang outofmemoryerror java heap space

Как бороться с ошибкой «java.lang.OutOfMemoryError: Java heap space»?

Я пишу клиентское приложение Swing (графический дизайнер шрифтов) на Java 5. В последнее время я столкнулся с ошибкой java.lang.OutOfMemoryError: Java heap space , потому что я не консервативен в использовании памяти. Пользователь может открывать неограниченное количество файлов, а программа сохраняет открытые объекты в памяти. После быстрого исследования я нашел эргономику в виртуальной машине 5.0 Java, а другие, говорящие на машине Windows, имеют максимальный размер кучи JVM как 64MB . Учитывая эту ситуацию, как мне решить эту проблему? Я могу увеличить максимальный размер кучи с помощью параметра командной строки для java, но для этого потребуется выяснить доступную оперативную память и написать какую-то программу запуска или script. Кроме того, увеличение до некоторого конечного максимума в конечном итоге не устраняет проблему. Я мог бы переписать часть моего кода, чтобы часто сохранять объекты в файловой системе (с использованием базы данных — одно и то же), чтобы освободить память. Это может сработать, но это, вероятно, тоже много работает. Если бы вы могли указать мне на подробности вышеизложенных идей или на некоторые альтернативы, такие как автоматическая виртуальная память, динамически расширяющая размер кучи, это будет здорово.

Читайте также:  Рамка с фоном css

Максимальный размер кучи по умолчанию составляет 64 МБ, начиная с версии J2SE 5.0. Информацию о J2SE 8.0 см. В разделе «Эргономика сборщика мусора» по адресу docs.oracle.com/javase/8/docs/technotes/guides/vm/… .

Если вы попали сюда из-за того, что каждый вопрос OOM дублирован на этот вопрос, обязательно проверьте также: stackoverflow.com/questions/299659/… Он предоставляет решение для очистки ссылок на память «как раз вовремя» перед OOM. SoftReferences может быть инструментом, который решает вашу актуальную проблему.

18 ответов

В конечном итоге у вас всегда есть конечная максимальная куча для использования независимо от того, на какой платформе вы работаете. В Windows 32 бит это около 2 ГБ (не в кучу, а общий объем памяти на процесс). Просто случается, что Java хочет уменьшить размер по умолчанию (предположительно, чтобы программист не мог создавать программы, у которых есть выделенное выделение памяти, не сталкиваясь с этой проблемой, и нужно точно изучить, что они делают).

Итак, это дает несколько подходов, которые вы могли бы предпринять, чтобы определить, какой объем памяти вам нужен или уменьшить объем используемой памяти. Одна распространенная ошибка с сборками мусора, такими как Java или С#, заключается в том, чтобы поддерживать ссылки на объекты, которые вы больше не используете, или выделять многие объекты, когда вы можете их повторно использовать. Пока объекты ссылаются на них, они будут продолжать использовать кучу пространства, так как сборщик мусора не удалит их.

В этом случае вы можете использовать профилировщик памяти Java, чтобы определить, какие методы в вашей программе распределяют большое количество объектов, а затем определить, есть ли способ убедиться, что они больше не ссылаются или не выделять их в первое место. Одним из вариантов, который я использовал в прошлом, является «JMP» http://www.khelekore.org/jmp/.

Читайте также:  Css отображение элемента поверх другого

Если вы определяете, что вы распределяете эти объекты по какой-либо причине, и вам нужно поддерживать ссылки (в зависимости от того, что вы делаете, это может быть так), вам просто нужно увеличить максимальный размер кучи при запуске программа. Однако, как только вы выполняете профилирование памяти и понимаете, как ваши объекты распределяются, вы должны иметь лучшее представление о том, сколько памяти вам нужно.

В общем случае, если вы не можете гарантировать, что ваша программа будет работать в некотором конечном объеме памяти (возможно, в зависимости от размера ввода), вы всегда столкнетесь с этой проблемой. Только после исчерпания всего этого вам нужно будет искать объекты кэширования на диске и т.д. На этом этапе у вас должна быть очень веская причина сказать «Мне нужно Xgb памяти» для чего-то, и вы не можете обойти его, улучшив ваши алгоритмы или шаблоны распределения памяти. Обычно это обычно будет иметь место для алгоритмов, работающих на больших наборах данных (например, в базе данных или в какой-либо программе научного анализа), а затем становятся полезными такие методы, как кэширование и отображение IO с памятью.

Источник

Builds running out of memory?

As your project grows, and you use new tools to either build or analyze your code, you will inevitably exceed the memory settings which your JVM provides by default. This is especially true on 64 bit JVM’s since they double the size of the reference pointer. This page aims to show you how to increase the memory available to your build process.

Heap or Permgen?

There are two OutOfMemoryErrors which people usually encounter. The first is related to heap space: java.lang.OutOfMemoryError: Heap space When you see this, you need to increase the maximum heap space. You can do this by adding the following to your JVM arguments -Xmx200m where you replace the number 200 with the new heap size in megabytes.

The second is related to PermGen: java.lang.OutOfMemoryError: PermGen space . When you see this, you need to increase the maximum Permanent Generation space, which is used for things like class files and interned strings. You can do this by adding the following to your JVM arguments -XX:MaxPermSize=128m where you replace the number 128 with the new PermGen size in megabytes.

Various Build Tools

This section demonstrates how to set these JVM switches depending on the kind of build you are running.

Maven2/3 Project Type

If you are using a Maven2/3 project type, you can set the -Xmx or -XX:MaxPermSize in your Jenkins global configuration. To do this, navigate to Jenkins global configuration page (Manage Jenkins -> Configure System) and look for the Maven Project Configuration. Add the necessary JVM settings to the Global MAVEN_OPTS field and press save. Subsequent Maven2/3 builds will use these new settings.

You can adjust the MAVEN_OPTS individually per job by navigating to the job, then clicking «configure» on the job menu, then under the «Build» section clicking advanced, then specifying a setting for the MAVEN_OPTS option.

Freestyle projects with Maven Build Steps

If you have a Freestyle project with a «Invoke Top Level Maven Targets» build step, you can add the appropriate JVM switches for a given build by clicking the Advanced button on the build step and entering the JVM arguments in the JVM Options field.

Alternatively, you can affect all free style Maven build steps by adding a MAVEN_OPTS global environment variable in the Jenkins global configuration. To do this, click Manage Jenkins, then Configure System. In the Global properties section, click the Environment Variables checkbox, then add a new environment variable called MAVEN_OPTS with the value set appropriately:

Gradle build steps

You can set the -Xmx or -XX:MaxPermSize by adding a GRADLE_OPTS global environment variable in the Jenkins global configuration. To do this, click Manage Jenkins, then Configure System. In the Global properties section, click the Environment Variables checkbox, then add a new environment variable called GRADLE_OPTS with the value set appropriately, similar to the screen shot above regarding MAVEN_OPTS

Ant build steps

For Ant steps, there is no global environment variable; you must set the Ant options in each individual build step. In the configuration for the build, find the Invoke Ant step, click Advanced, and enter the options into the Java Options box.

Источник

java.lang.outofmemoryerror: java heap space | How to Fix?

How to solve java.lang.outofmemoryerror: java heap space or exception in thread “main”? Know reasons caused by and how to solve it guide.

Introduction

In Java JVM allocates a defined memory size for storing objects created during program execution known as Java Heap Space. Along with it, JVM allocates another memory called PermGen space: permanent generation space.

java.lang.outofmemoryerror java heap space

However, we can change the default size with the JVM options.

Most importantly, Oracle completely removed this memory space in the JDK 8 release.

Java 8 memory management heap

Memory space in the JDK 8 release

Understanding OutOfMemoryError in Java

There most common reason for this error is simple –

If we try to fit a large application into a smaller space. In other words, the application just requires more Java heap space than available to it to operate normally.

Other causes:

  1. 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 the expected limit. The operation which functioned normally before the spike ceases to operate and triggers the OutOfMemoryError.
  2. 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 in the Java heap space. Over time the leaked objects consume all of the available heap space and trigger the already familiar OutOfMemoryError.

Exception in thread “main” java.lang.outofmemoryerror: java heap space

Exception in thread "main" java.lang.OutOfMemoryError

What is causing it?

Generally, bad programming results in OutOfMemoryError. OutOfMemoryError usually means that we’re doing something wrong, either holding onto objects too long or trying to process too much data at a time. Sometimes, it indicates a problem that’s out of our control, such as a third-party library that caches strings, or an application server that doesn’t clean up after deploys.

GC Overhead limit exceeded- This error indicates that the garbage collector is running all the time and the Java program is making very slow progress. If such an event occurs then an OutOfMemoryError is thrown.

Stack vs Java Heap Space

Heap Space
Whenever we create an object, it’s always created in the Heap space.

Stack Memory
Java Stack memory is used for the execution of a thread. It also contains method references.

Note: String Pool is also a part of Java Heap Memory.

Solving java.lang.outofmemoryerror: java heap space error

Increase Java Heap size in Java

The default size of Heap space in Java is 128MB on most of 32 bit Sun’s JVM but it highly varies from JVM to JVM.

For instance, the default maximum and start heap size for the 32-bit Solaris Operating System (SPARC Platform Edition) is -Xms=3670K and -Xmx=64M. And default values of heap size parameters on 64-bit systems have been increased up by approximately 30%.

Also, if we are using a throughput garbage collector in Java 1.5 default maximum heap size of JVM would be Physical Memory/4, and the default initial heap size would be Physical Memory/16.

Another way to find the default heap size of JVM is to start an application with default heap parameters and monitor using JConsole. It is available on JDK 1.5 onwards, on the VMSummary tab, you will be able to see the maximum heap size.

Moreover, we can increase the size of java heap space based on our application need and it is always recommended to avoid using default JVM heap values. Therefore, if our application is large and lots of objects are created. We can change the size of heap space by using JVM options -Xms and -Xmx. Here, Xms denotes the starting size of Heap while -Xmx denotes the maximum size of Heap in Java.

There is another parameter called -Xmn. It denotes the size of the new generation of Java Heap Space. The only thing is we can’t change the size of Heap in Java dynamically. We can only provide the Java Heap Size parameter while starting JVM.

Conclusion

We hope you got your error resolved. Let us know by commenting if you need any help or have any questions.

If this article helped you feel free to share. Keep reading and sharing. Kudos!!

Источник

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