- 7 наиболее распространенных ошибок при установке ограничений памяти Java
- How to control Java heap size (memory) allocation (xmx, xms)
- Java RAM: Short answer
- Java RAM: The longer answer
- Setting the maximum Java heap size (Xmx)
- More Java memory-related command line arguments
- Java heap size descriptions (xms, xmx, xmn)
- Java memory arguments (xms, xmx, xmn) formatting (MB, GB)
- Default Java Maximum Heap Size is changed for Java 8
- Changes to default Java Maximum Heap Size for Java 8
- Verify Maximum Heap Size
- Share this:
7 наиболее распространенных ошибок при установке ограничений памяти Java
Для установки размера кучи java (heap) используются две опции: -Xmx для установки максимального размера и -Xms для начального(минимального) размера. Вот наиболее часто встречающиеся ошибки их использования:
1. Отсутствие m, M, g или G в конце (регистр не имеет значения). Например:
java -Xmx128 BigApp
java.lang.OutOfMemoryError: Java heap space
Строго говоря, -Xmx128 корректная настройка для очень маленьких приложений (например HelloWorld), но я думаю в большинстве случаев все-таки имелось в виду -Xmx128m.
2. Лишний пробел или использование =. Например:
java -Xmx 128m BigApp
Invalid maximum heap size: -Xmx
Could not create the Java virtual machine.
java -Xmx=512m HelloWorld
Invalid maximum heap size: -Xmx=512m
Could not create the Java virtual machine.
без пробела или знака =. -X опции ведут себя отлично от -Dключ=значение опций, в которых используется =.
3. Установка только -Xms в значение большее чем максимальный размер кучи по умолчанию (64m). Похоже что минимальный размер кучи по умолчанию равен 0.
Пример:
java -Xms128m BigApp
Error occurred during initialization of VM
Incompatible initial and maximum heap sizes specified
java -Xms128m -Xmx128m BigApp
Установить минимальный и максимальный размер равными — хорошая идея. В любом случае, минимальное значение не должно превышать максимальное.
4. Установка размера кучи большего чем объем доступной физической памяти. Пример:
java -Xmx2g BigApp
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
java -Xms256mb -Xmx256mb BigApp
Invalid initial heap size: -Xms256mb
Could not create the Java virtual machine.
java -Xmx256g BigApp
Invalid maximum heap size: -Xmx256g
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.
java -Xmx0.9g BigApp
Invalid maximum heap size: -Xmx0.9g
Could not create the Java virtual machine.
Как установить размер кучи(heap) в Tomcat?
Остановите сервер Tomcat, установите переменную окружения CATALINA_OPTS, затем запустите Tomcat снова. Смотрите файлы tomcat-install/bin/catalina.sh или catalina.bat чтобы узнать как используется эта переменная окружения.
set CATALINA_OPTS=-Xms512m -Xmx512m
export CATALINA_OPTS="-Xms512m -Xmx512m"
setenv CATALINA_OPTS "-Xms512m -Xmx512m"
(tcsh/csh, значение в кавычках)
Просмотрев catalina.bat или catallina.sh, вы можете заметить что для установки JVM опций использутся CATALINA_OPTS, JAVA_OPTS или и то и другое. В чем же различие между CATALINA_OPTS и JAVA_OPTS? Имя CATALINA_OPTS специфично именно для Tomcat, а JAVA_OPTS может использоваться и в других java приложениях (например Jboss). Так как переменные окружения как правило устанавливаются глобально, Вы можете использовать это CATALINA_OPTS задания опций для Tomcat, и JAVA_OPTS — для опций других приложений.
Я предпочитаю использовать CATALINA_OPTS.
Как установить размер кучи в JBoss?
Остановите Jboss, отредактируйте значения в файле $JBOSS_HOME/bin/run.conf, запустите сервер. Вы можете изменить (или добавить если ее там нет) значение переменной JAVA_OPTS например на такое: JAVA_OPTS=»-server -Xms128m -Xmx128m»
Как установить размер кучи в Eclipse?
Запускайте Eclispe с ключем «-vmargs «. Все опции после -vmargs будут интерпретированы как опции JVM.
Пример:
eclipse -vmargs -Xms64m -Xmx256m
Это установит опции для Eclipse, но не для приложения которое Вы разрабатываете в eclipse. Для того чтобы поменять опции приложения, используйте Run As -> Open Run Dialog -> (x)=Arguments -> VM Arguments
Как установить размер кучи в NetBeans?
Закройте NetBeans, отредактируйте файл netbeans-install/etc/netbeans.conf. Пример:
netbeans_default_options brush: bash">set ANT_OPTS=-Xms512m -Xmx512m
export ANT_OPTS="-Xms512m -Xmx512m"
setenv ANT_OPTS "-Xms512m -Xmx512m"
Как установить размер кучи в JavaEE SDK/J2EE SDK/Glassfish/Sun Java System Application Server?
Остановите сервер приложений, откройте $GLASSFISH_HOME/domains/domain1/config/domain.xml, найдите там XML элемент с именем java-config -> jvm-options. Пример:
-Xmx512m
-XX:NewRatio=2
-XX:MaxPermSize=128m
.
Также вы можете изменять опции через веб-интерфейс администратора, обычно http://localhost:4848/, или https://localhost:4848/. Откройте Application Server в верхней части левой панели, затем на правой панели откройте JVM Settings -> JVM Options, и Вы увидите список текущих опций. Вы можете добавить новые или изменить существующие.
Еще один способ — использование cli комманды. Смотрите справку:
./asadmin help create-jvm-options
./asadmin help delete-jvm-options
How to control Java heap size (memory) allocation (xmx, xms)
Java/Scala memory FAQ: How do I control the amount of memory my Java program uses (i.e., Java RAM usage)?
Java RAM: Short answer
The short answer is that you use these java command-line parameters to help control the RAM use of application:
- Use -Xmx to specify the maximum heap size
- Use -Xms to specify the initial Java heap size
- Use -Xss to set the Java thread stack size
Use this syntax to specify the amount of memory the JVM should use:
-Xms64m or -Xms64M // 64 megabytes -Xmx1g or -Xmx1G // 1 gigabyte
A complete java command looks like this:
See the rest of this article for more details. Also see my Java heap and stack definitions if you’re not comfortable with those terms.
Java RAM: The longer answer
As a bit of background, I’m running a Java application on a Raspberry Pi device where memory is limited. Unfortunately, every time I try to run the program I get this Java heap size error message:
“Error occurred during initialization of VM. Could not reserve enough space for object heap. Could not create the Java virtual machine.”
I knew my program doesn’t need a lot of memory — it was just hitting a database and generating some files and reports — so I got around this memory limit problem by specifying the maximum Java heap size my program was allowed to allocate. In my case I didn’t think about it too hard and just chose a heap size limit of 64 MB RAM, and after I set this RAM limit my program ran fine.
Setting the maximum Java heap size (Xmx)
You set the maximum Java heap size of your program using the -Xmx option to the Java interpreter. To specifically limit your heap size to 64 MB the option should be specified like this:
Using that memory limit setting, the Java command I use in my shell script to start my Java program looks like this:
where THE_CLASSPATH and PROGRAM_NAME are variables set earlier in my script. (The important part here is the -Xmx64m portion of the command.)
More Java memory-related command line arguments
You can find more options for controlling Java application memory use by looking at the output of the java -X command. Here’s what the output of those commands looks like from my JVM:
$ java -X -Xmixed mixed mode execution (default) -Xint interpreted mode execution only -Xbootclasspath:set search path for bootstrap classes and resources -Xbootclasspath/a: append to end of bootstrap class path -Xbootclasspath/p: prepend in front of bootstrap class path -Xnoclassgc disable class garbage collection -Xloggc: log GC status to a file with time stamps -Xbatch disable background compilation -Xms set initial Java heap size -Xmx set maximum Java heap size -Xss set java thread stack size -Xprof output cpu profiling data -Xfuture enable strictest checks, anticipating future default -Xrs reduce use of OS signals by Java/VM (see documentation) -Xdock:name= override default application name displayed in dock -Xdock:icon= override default icon displayed in dock -Xcheck:jni perform additional checks for JNI functions -Xshare:off do not attempt to use shared class data -Xshare:auto use shared class data if possible (default) -Xshare:on require using shared class data, otherwise fail. The -X options are non-standard and subject to change without notice.
From that list, the command-line arguments specifically related to Java application memory use are:
-Xnoclassgc disable class garbage collection -Xmsset initial Java heap size -Xmx set maximum Java heap size -Xss set java thread stack size
Java heap size descriptions (xms, xmx, xmn)
Digging around, I just found this additional Java xms , xmx , and xmn information on Apple’s web site:
-Xms size in bytes Sets the initial size of the Java heap. The default size is 2097152 (2MB). The values must be a multiple of, and greater than, 1024 bytes (1KB). (The -server flag increases the default size to 32M.) -Xmn size in bytes Sets the initial Java heap size for the Eden generation. The default value is 640K. (The -server flag increases the default size to 2M.) -Xmx size in bytes Sets the maximum size to which the Java heap can grow. The default size is 64M. (The -server flag increases the default size to 128M.) The maximum heap limit is about 2 GB (2048MB).
Java memory arguments (xms, xmx, xmn) formatting (MB, GB)
When setting the Java heap size, you should specify your memory argument using one of the letters “m” or “M” for MB, or “g” or “G” for GB. Your setting won’t work if you specify “MB” or “GB.” Valid arguments look like this:
Also, make sure you just use whole numbers when specifying your arguments. Using -Xmx512m is a valid option, but -Xmx0.5g will cause an error.
Default Java Maximum Heap Size is changed for Java 8
The Maximum Java Heap Size (Xmx) is the maximum amount of memory that Java application can uses. A lower Xmx value will cause a decrease in performance due to JVM has to force frequent garbage collections in order to free up space, also if the Xmx value is lower than the amount of live data, it might trigger OutOfMemoryError. Customers can configure Xmx via JVM options -Xmx to optimize their Java application performance, but quite a lot of Java users never explicitly specify the -Xmx option, so in those cases the default Xmx has been used. The default values for Xmx is based on the physical memory of the machine.
In current OpenJ9 release 0.19:
For Java 11 and above
The Xmx value is 25% of the available memory with a maximum of 25 GB. However, where there is 2 GB or less of physical memory, the value set is 50% of available memory with a minimum value of 16 MB and a maximum value of 512 MB.
For Java 8
The Xmx value is half the available memory with a minimum of 16 MB and a maximum of 512 MB.
Changes to default Java Maximum Heap Size for Java 8
From OpenJ9 release 0.20, The default Java Maximum Heap Size (Xmx) is changed to be consistent with Java 11, so by default in Java 8, 25% physical memory up to 25GB for the Xmx will be expected. If you want to revert to the default setting in earlier releases of OpenJ9, use the -XX:+OriginalJDK8HeapSizeCompatibilityMode option.
-XX:[+/-]OriginalJDK8HeapSizeCompatibilityMode is new option for release 0.20, but it is deprecated and should only be used in case you want to keep earlier releases behavior of default Xmx.
Keep in mind this change only affect the behavior of the default Xmx in Java 8 and there is no change for Java 11 and above. the option -XX:[+/-]OriginalJDK8HeapSizeCompatibilityMode is also ignored in Java 11 and above.
Verify Maximum Heap Size
If you want to confirm maximum heap size for your OpenJ9 release in runtime, you can simply verify the default max heap size via -verbose:gc options. you can find out the result in initialized section of verbosegc.
For OpenJ9 Java8 release 0.19 or earler, On 4GB physicalMemory machine the default Xmx is 512MB.
For OpenJ9 Java8 release 0.20, On 4GB physical memory machine the default Xmx is 1GB.