Error occurred during initialization of vm could not reserve enough space for 1048576kb object heap

Describe the bug Try to start some simple Main class with Xmx set to 1G with 32-bit Corretto JVM 8.0_222 and it will fail with error: Error occurred during initialization of VM Could not reserve en...

Hi @pavelsher

Can you try to disable Tiered Compilation with Corretto and try it again? The JVM parameter to disable it is:

The reason you could achieve higher heap size with other distributions was because on Windows x86 they have both Client and Server VMs and use the Client VM by default, while Corretto only has the Server VM at the moment. However, running TeamCity with the Client VM means it would be running with less optimized code compiled by C1.

What makes the difference here is the Code Cache used by the JIT compiler. Since JDK8, Tiered Compilation is enabled by default in the Server VM, and increased the ReservedCodeCacheSize to 240Mb, while the default value is just 32Mb for the Client VM and 48Mb for the Server VM without Tiered Compilation. When I set it explicitly to 48Mb with Corretto on the Server VM:

-XX:ReservedCodeCacheSize=48M

I can achieve the similar heap size as other distributions.

However, it is NOT safe to do so with real applications. Tiered Compilation would require more Code Cache. Normally it might require 4-10 times more Code Cache than C2. If you just simply restrict the ReservedCodeCacheSize, it would run out of Code Cache pretty soon and you will see the following error message:

CodeCache is full. Compiler has been disabled

The safe option here is disabling Tiered Compilation. In this way, it can have a similar heap size as the Client VM, at the same time use more optimized code from C2 while running the service. One of the downsides might be that it would require more CPU at the startup. If the CPU cost at the startup time is not an issue for your application, it might be the perfect solution.

We have also tried to build Corretto with both Client and Server VMs on Windows x86. It worked fine and achieved similar result as other distributions. However, we would have to justify whether that gonna be the way to going forward, or the Server VM would be good enough for users.

Please let us know the result of your experiment.

Sometimes we get could not reserve enough space for object heap error when we run a java application. This is a JVM error occurs for the reasons listed below. Before diving deep into the topic lets understand JVM heap space first.

Understanding JVM heap space:

Limited memory is allocated in JVM to run a java application. The memory is specified during the startup of applications.

Read Also:  Java.net.ConnectException: Connection Refused

 -Xms is a VM option to specify heap memory. Heap size can be fixed or variable depending on the strategy of garbage collection. Maximum heap size can be specified by -Xmx option.

The main cause of heap memory error occurs for the following three reasons:

Reason 1:

If we run a java application without specifying memory we can get this kind of error.
The error should be like this.

Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

Solution:

Most of the time this error occurs for 32 bit JVM. Because 32 bit JVM requires free space in memory to run the application but many times there is not enough memory to run java application.

We should replace 32 bit JVM with 64 bit JVM in a 64-bit computer to resolve this issue or we can specify memory to run the application by using below command

java -Xmx256M JavaApplication

Reason 2:

If we assign memory to 32 bit JVM greater than the heap size of the JVM, we can get this kind of error.

Suppose our JVM heap memory size is 2006M and we also assign the same size when we execute the program, we will get heap size error. For example, if we execute the following command, we will get
error in 32-bit JVM.

java -Xms2006M -Xmx2006M JavaApplication

Solution:

We should specify smaller memory as heap memory in 32 bit JVM as shown below or we should use 64 bit JVM

java -Xms1336M -Xmx1336M JavaApplication

Reason 3:

If we specify heap memory more than our physical memory, we will get this kind of error. Suppose we have 2GB ram but if we execute the following command we will get the error.

java -Xms8192M -Xmx8192M JavaApplication

Solution:

We can get rid of this error by specifying a smaller heap memory.

java -Xms1336M -Xmx1336M JavaApplication

Another way to resolve this issue, we should specify memory size in the _JAVA_OPTIONS variable in the path of the operation system. When we run the Java application it will take the memory size from the path. This path data should overcome the problems described above.

For Linux:

-bash-3.2$ export _JAVA_OPTIONS="-Xmx256M"
-bash-3.2$ javac JavaApplication.java

For Windows:

Follow the below path:
Start -> Control Panel -> System -> Advance(tab) -> Environment Vairables -> System Variables ->
Create  New Variable Name: _JAVA_OPTIONS -> Variable Value: -Xmx256M

Nowadays, 64 bit systems are available. We should avoid 32-bit hardware architecture and 32-bit java versions.

That’s all for today, please mention in comments in case you have any questions related to could not reserve enough space for object heap error.

In this post, we will see an error(Could not reserve enough space for 2097152kb object heap object heap) which you might have encountered while dealing with JVM.We will see how can we fix this issue.

Table of Contents

  • Heap size
    • Maximum heap size
  • Cause 1: Did not specify heap size
    • Fix 1
  • Cause 2: Too large Xmx value
    • Fix 2
  • Cause 3: Specifying large heap size more than physical memory
    • Fix 3
    • Set _JAVA_OPTIONS environment variable
  • Could not reserve enough space for 2097152kb object heap
    • Apache cordova
    • Minecraft
    • Jfrog artifactory
  • Conclusion

error occurred during initialization of vm could not reserve enough space for 2097152kb object heap is generally raised when Java process can not create java virtual machine due to memory limitations.

Before we go through causes and fixes for this issue, let’s go through few basic things.

Heap size

Heap size is memory allocation space for storing java objects at run time. This heap size can have minimum and maxiumn heap size. You can specify minimum and maximum size using Xmx and Xms VM arguments.

Maximum heap size

The maximum possible heap size can be determined by available memory space. It is different on 32 bit and 64 bit as follows.

  1. 2^32 (~4GB) on 32 bit JVM
  2. 2^64 (~16EB) on 64 bit JVM.

In general, you will get 1.4-1.6 GB on 32 bit windows and approximately 3GB on on 32 bit linux.

If you require large heap, then you should generally use 64 bit JVM.

Cause 1: Did not specify heap size

Let’s say you run your java program without specifying any heap size and you get below error.

Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

You will get this error more often in 32 bit JVM rather than 64-bit JVM

Reason
32-bit Java requires contiguous free space in memory to run. If you specify a large heap size, there may not be so much contiguous free space in memory even if you have much more free space available than necessary.
Installing 64-bit version might solve this issue in this case.

Fix 1

You can fix this error by running Java with lower heap size such as -Xmx512m.

java Xmx512M MyApplication

Cause 2: Too large Xmx value

If you specify too large memory with -Xmx option on 32 bit VM, you may also get this error.
For example:
Let’s say you are getting an error with below execution.

java Xms1536M Xmx1536M MyApplication

Fix 2

You might not have enough contiguous free space in memory.You can run the application with slightly lower heap size to resolve the issue.

javaXms1336M Xmx1336M MyApplication

Cause 3: Specifying large heap size more than physical memory

If you specify large heap size more than physical memory available on 64-bit or 32-bit  machine, you will get this error.
For example:
Let’s say You have 3 GB RAM on your machine and you are executing below command, you will get this error.

java Xms4096M Xmx4096M MyApplication

Fix 3

You can run the application with heap size which is less than your physical memory.

javaXms2048M Xmx2048M MyApplication

Sometimes above solutions might not work.

Set _JAVA_OPTIONS environment variable

So you can set _JAVA_OPTIONS as the environment variable.

In Linux

-bash-3.2$ export _JAVA_OPTIONS =»-Xmx512M»
-bash-3.2$ javac MyApp.java

In Window

Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System
Variables->New: Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M

💡 Did you know?

JDK_JAVA_OPTIONS is prefered environment variable from Java 9+ onward to specify Java options. It will be ignored in the version lesser than Java 9.

You might get an specific error Could not reserve enough space for 2097152kb object heap in case you are using any tool. It simply means that JVM is not able to acquire 2 GB heap space which is required by the tool by default.

Apache cordova

Apache Cordova is a mobile application development framework originally created by Nitobi.
If you are getting this error on Apache cordova, here are solutions.

  1. Switch from 32 bit JVM to 64 bit JVM
  2. set _JAVA_OPTIONS environment variable with -Xmx512M
  3. Change

    args.push(‘-Dorg.gradle.jvmargs=-Xmx2048m’)

    to  

    args.push(‘-Dorg.gradle.jvmargs=-Xmx1024m’);

    on the following files located on your machine.

    project-folderplatformsandroidcordovalibbuildersbuilders.js
    project-folderplatformsandroidcordovalibbuildersGradleBuilder.js
    project-folderplatformsandroidcordovalibbuildersStudioBuilder.js

Minecraft

If you are getting this error, while launching Minecraft game, then you need to switch from 32 bit JVM to 64 bit JVM.

Jfrog artifactory

If you are using JFrom artifactory as artifact life-cycle management tool and getting Could not reserve enough space for 2097152kb object heap while launching it.
Go to bin directory of your JFrog Artifactory installation, change following line in arifactory.bat file.

set JAVA_OPTIONS=-server Xms512m Xmx2g Xss256k XX:+UseG1GC

to

set JAVA_OPTIONS=-server Xms512m Xmx1024m Xss256k XX:+UseG1GC

This should resolve this error for JFrog Artifactory installation.

Conclusion

  • If you might have installed 32 bit JVM in 64 bit machine.Upon uninstalling that version and installing 64 bit version of Java
  • You might have provided too large heap size which might be greater than physical memory. In this case, you need to reduce heap size of JVM.
  • If above solution does not work, you can set JAVA_OPTS as the environment variable to solve this issue. If you set JAVA_OPTS environment variable, then each JVM initialization will automatically use configuration from this environment variable

I hope this will resolve your issue with error occurred during initialization of vm could not reserve enough space for 2097152kb object heap.

Problem

Could not reserve enough space for object heap

Symptom

This is noticed when you try to start a JVM.
This could occur due to two possible reasons

1. java -Xmx parameter is incorrectly.

The parameter -Xmx denotes the maximum value
that the heap can grow. A range of addresses equal in size to
the -Xmx value is reserved at startup so the JVM can grow to the maximum heap
size.
The value set in this parameter is limited by the OS used.
For windows, the maximum heap that can be used per process is 1.2 GB to 1.5 GB.

2. The amount of memory
available to java

It could be
possible that several other applications are consuming memory due to which this
JVM is not able to reserve the specified amount of memory.

Error Message

Error occurred during initialization of
VM
Could not reserve enough space for object
heap

Resolving The Problem

Solution

1. If the issue occurs due to incorrect -Xmx
value, make sure that the limitation mentioned above is considered and then the
value is set.

2. If this
application is not able to reserve sufficient memory, make sure that there are
no other processes which is consuming a huge chunk of memory. If there are,
probably bringing them down would help resolve the issue.

[{«Product»:{«code»:»SS6QYM»,»label»:»Sterling Selling and Fulfillment Suite»},»Business Unit»:{«code»:»BU055″,»label»:»Cognitive Applications»},»Component»:»Not Applicable»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»All»,»Edition»:»»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}}]

Historical Number

TRB2873

Even though Java applets aren’t a popular web technology these days, there are countless reasons to deploy a Java virtual machine directly on a Linux server. If you try to run the Linux java command outright either on discrete hardware or inside of its own VM, then you might get an “error occurred during initialization of VM could not reserve enough space for object heap” message.

This probably looks rather odd because you more than likely have enough RAM to run the command, but it’s largely due to a specific quirk in the way that physical and virtual memory pages get used. Specifying some relatively large sizes should allow you to completely bypass this message and run the java command the way you would any other.

Method 1: Using Command Line Options

If you’ve tried to run java and gotten this message, then you’ve probably already run the free command to make sure that there’s ample supplies of memory to run the program in.

java & free commands

Notice that on our test machine we had some 2.3 GB of physical RAM and not a single page of virtual memory had gotten used yet. If you notice that you have a memory crunch, then you’ll want to close other things that you have running before trying it again. On the other hand, those who found that they have plenty of free memory can try to specify a size directly.

For example, on our machine we were able to run the command as java -Xms256m -Xmx512M and it worked like it would have otherwise been expected to. This constrains the heap size that the Java virtual machine attempts to reserve on startup. Since an unrestrained virtual machine could hypothetically do unusual things, it might throw error messages on an otherwise free system. You may also want to play around with those two values before you find the right combination.

This can be an issue regardless of what you’re running it on since the JVM has nothing to do with the type of VM you might be using to run GNU/Linux.

Method 2: Exporting the Variables to Make the Change Permanent

When you find a value that works you can export it to make it permanent for that session. For instance, we used export _JAVA_OPTIONS=’-Xms256M -Xmx512M’ from the bash command prompt and it allowed us to run the java command by itself without any other options until we logged out of our server.

It needed to be run again when we logged in another session, so you might want to add it to any relevant startup scripts if you plan to be using the java command quite often. We added the line to our .bash_login file and it seemed to work each time we used a login prompt without having to run it again, though you might have to find another location for it if you’re working with a different shell.

You may have noticed that only certain hardware configurations trigger this error message. That’s because it usually happens on machines with a great deal of physical RAM but lower ulimits for how to use it. Java will try to allocate a huge block only to be told it can’t, which it interprets as running out of memory.

Method 3: Printing Current Java Options

If you’ve been working at the command line and want a quick reference to what you’ve currently set the _JAVA_OPTIONS value to, then simply run echo $_JAVA_OPTIONS and it will immediately print out the current values. This is useful for troubleshooting when you’re trying to figure out the right numerals to try.

Keep in mind that while this fix shouldn’t require any other playing around, Java will throw out the “could not reserve enough space for object heap” message if you ever find yourself genuinely on the short end of virtual memory. If this is the case, then you’ll want to double check what processes are currently running and possibly restart the server if that’s an option. You could also create more swap space, but if this is an issue it’s generally better to try and correct it in some other way.

In the rare case that your settings seem to be right but it still isn’t working, make sure you’ve installed the 64-bit Java package since it should be immune to this problem. Contiguous memory requirements only apply to the 32-bit version of Java. We found in a handful of cases the 64-bit version tried to create a 32-bit virtual machine, so specifying the -d64 option on the command line fixed it for us.

Photo of Kevin Arrows

Kevin Arrows

Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

Сегодня существует не так много хороших и стабильных лаунчеров для популярной игры Minecraft. Один из них — разработанный в 2013 году продукт TLauncher. Программа выполняет рад функций, без которых невозможно не только запустить игру в сессии онлайн, но и просто войти в свой аккаунт. TLauncher отвечает за идентификацию пользователя на сервере, следит за актуальностью версий, обновляет их. Скрипт автоматически подгружает все необходимые Java-библиотеки для стабильной работы клиента, позволяет бесплатно скачивать любые версии  Minecraft с серверов разработчиков напрямую, а также запускать “пиратские” версии игры. Существуют платные и бесплатные версии TLauncher. Несмотря на все свои достоинства, у некоторых пользователей возникают ошибки tlauncher при запуске. Именно о том, как действовать в таких ситуациях, поговорим в данной статье.

Обновление библиотеки Java

TLauncher напрямую взаимодействует с программной платформой Java, по умолчанию предустановленной в Windows. В случае возникновения проблем с лаунчером, прежде всего следует актуализировать версию Джава. Предварительно удалите текущую версию, произведите очистку реестра. Затем скачайте актуальную утилиту с официального сайта java.com, инсталлируйте ее. Конфликт и ошибки чаще всего возникают у юзеров с ОС Виндовс 10, особенно при использовании устаревшей версии Java, после установки очередного мода от ненадежного разработчика.

Подробнее об этом читайте в статье: Как обновить Java в Windows 10.

обновить Java в Windows 10

Для полной уверенности после переустановки Java рекомендуется заново скачать TLauncher и клиент игры, установить их на компьютер.

Обновление операционной системы

Часто пользователи принудительно отключают автоматические обновления Windows, дабы избежать их работы в фоновом режиме. Это приводит к появлению различных ошибок в системе, особенно при регулярной установке на компьютер сторонних приложений и программ. Одной из проблем может стать ошибка запуска TLauncher. Чтобы проверить актуальность релиза Виндовс, выполните следующие действия.

  1. В меню “Пуск” запустите приложение “Параметры”.

запустите приложение “Параметры”

2. Перейдите во вкладку “Обновление и безопасность”.

“Обновление и безопасность

3. Нажмите кнопку “Проверить наличие обновлений”.

Проверить наличие обновлений

В следующем окне увидите рекомендации по обновлениям, также здесь можно поменять настройки политики обновления Виндовс. Выполните актуализацию операционной системы и перезагрузите компьютер.

Удаление обновления KB4515384

Парадоксальность взаимодействия TLauncher и Windows заключена в том, что установка всех обновлений ОС может привести к конфликту лаунчера с некоторыми из них. В частности, разработчики лаунчера рекомендуют удалить конкретный апдейт Виндовс с кодом KB4515384 в случае возникновения ошибок.

  1. Для этого также войдите в “Центр обновлений Windows”, как указано в предыдущем разделе, перейдите в “Просмотр журнала обновлений”.Просмотр журнала обновлений
  2. Активируйте вкладку “Удалить обновления”. Если в открывшемся списке присутствует строка с кодом KB4515384, дважды щелкните по ней и подтвердите удаление.

Удалить обновления

При регулярном появлении ошибок конфликта TLauncher с обновлениями Windows, настройте ручную установку, либо полную блокировку апдейта. В качестве проверки наличия данного конфликта можно приостановить обновления на 7 дней в “Центре обновления Windows”. Для полной блокировки обновлений воспользуйтесь сторонней утилитой Win Updates Disabler.

Примечание. Использование сторонних приложений, особенно для блокировки процессов ОС Виндовс, может привести к серьезным сбоям в работе системы. Будьте внимательны при их использовании.

Отсутствие поддержки UTF-8

Одним из вариантов возникновения ошибки TLauncher при взаимодействии с компонентами Windows может быть конфликт использования алгоритмов кодов. В частности, отсутствие поддержки символов Юникода UTF-8. Для устранения проблемы поменяйте соответствующие настройки операционной системы.

  1. Откройте “Поиск” и наберите “Региональные параметры”наберите “Региональные параметры”
  2. В новом окне выберите “Дополнительные параметры даты, времени, региона” в “Сопутствующих параметрах”выберите “Дополнительные параметры даты, времени, региона”
  3. В “Региональных стандартах” нажмите на строку “Изменение форматов даты, времени и чисел”.В “Региональных стандартах” нажмите на строку “Изменение форматов даты, времени и чисел”
  4. Во вкладке “Дополнительно” нажмите на кнопку “Изменить язык системы”.Во вкладке “Дополнительно” нажмите на кнопку “Изменить язык системы”
  5. Теперь установите галочку напротив надписи “Бета-версия: Использовать Юникод (UTF-8) для поддержки языка во всем мире”, нажмите “ОК”.

установите галочку напротив надписи Бета-версия

Чтобы изменения вступили в силу перезагрузите компьютер. Проверьте, как работает TLauncher.

Активация ClearType

Проблема взаимодействия с кодировкой символов, способ ее решения описаны в предыдущем разделе. Иногда у TLauncher продолжает возникать конфликт со шрифтами даже после включения поддержки Юникода UTF-8. В этом случае решением может стать настройка функции ClearType.

  1. Через “Поиск” активируйте функцию “Настройка текста ClearType”.Настройка текста ClearType”
  2. Поставьте галочку напротив “Включить ClearType” и нажмите “Далее”. Запустите процесс и выполните пошагово все инструкции. Перезагрузите компьютер, чтобы применить изменения.

Поставьте галочку напротив Включить ClearType

Устаревший драйвер видеоконтроллера может привести к различным проблемам, связанным с корректной работой Minecraft. В частности, на это указывает частое зависание игры, “черный экран”, мигание текстуры на экране. Попробуйте актуализировать драйвер видеокарты стандартными инструментами Windows.

  1. Кликните правой кнопкой мыши в левом нижнем углу экрана “Пуск” и откройте “Диспетчер устройств”.откройте “Диспетчер устройств
  2. Выберите и откройте “Видеоадаптеры”, дважды кликнете по видеоконтроллеру. Далее во вкладке “Драйвер” нажмите “Обновить драйвер”.нажмите “Обновить драйвер”
  3. Запустите “Автоматический поиск драйверов” и дождитесь, когда система обновит программу. Далее перезагрузите компьютер.

Запустите “Автоматический поиск драйверов”

Для более кардинального решения проблемы с актуализацией необходимо удалить текущий драйвер и произвести установку нового с официального сайта производителя вашего видеочипа. Для этого придется выяснить его параметры конфигурации.

Примечание. Старые модели видеокарт могут не поддерживать последние релизы Minecraft в силу маломощности и приводить к ошибкам TLauncher. В этом случае выходом будет только физическая замена видеоплаты на современную.

Проблемы с антивирусом и Брандмауэром

Иногда пользователи жалуются, что TLauncher вылетает в процессе игры, соединение с сервером прерывается по непонятной причине. Аварийное завершение работы клиента без объяснимых причин может быть следствием блокировки доступа со стороны антивирусной программы и других приложений-посредников. Для решения проблемы попробуйте предпринять следующие действия:

  • полностью отключите антивирус на время игры, чтобы убедиться в том, что блокировка происходит по его причине;
  • добавьте исполнительный файл Minecraft в «Доверенную зону» вашего антивируса;
  • отключите полностью Брандмауэр Виндовс, либо запретите защитнику блокировку Майнкрафт.

Брандмауэр Виндовс

Учитывайте, что полное отключение защиты компьютера от угроз может привести к заражению вредоносным ПО и серьезным проблемам. Обязательно проводите полную проверку после такой блокировки антивируса и Защитника Виндовс.

Нехватка оперативной памяти

Одна из ошибок, которая не дает запуститься игре, в консоли TLauncher выдает запись:

Error occurred during initialization of VM

Could not reserve enough space for 1048576KB object heap

Java HotSpot (TM) Client VM warning: using incremental CMS…

Для устранения проблемы следует в “Настройках” — “Дополнительно” увеличить объем доступной оперативной памяти во вкладке “Выделение памяти”. Процесс лучше выполнять пошагово, каждый раз производя пробный запуск игры. См. также: Как очистить оперативную память на Windows 10.

Переустановка TLauncher

Довольно “простой” способ решения многих проблем с запуском лаунчера заключается в его обновлении через переустановку. Для этого необходимо вначале удалить программу стандартными методами Windows.

Войдите в “Параметры” — “Приложения и возможности”, найдите запись программы TLauncher и корректно удалите ее. Так же как в случае с деактивацией Java-приложения, рекомендуется произвести очистку реестра от следов присутствия лаунчера.

найдите запись программы TLauncher и корректно удалите ее

Перезагрузите компьютер. Установите свежую версию TLauncher с официального сайта .

Установите свежую версию TLauncher

Все предыдущие настройки придется делать заново. Но иногда это единственный способ решения проблем с ошибками TLauncher.

В заключение

В статье перечислены не все ошибки TLauncher, с которыми сталкиваются геймеры. Если у вас есть примеры других сложных ситуаций при использовании данного лаунчера для игры в Minecraft, поделитесь способами их решения в комментариях. Уверен, ваши соратники будут благодарны за полезные советы.

Post Views: 1 964

Понравилась статья? Поделить с друзьями:
  • Error occurred during initialization of boot layer ошибка eclipse
  • Error occurred during initialization of boot layer netbeans
  • Error occurred while erasing blocks при обновлении биос
  • Error occurred while enabling is it up to date
  • Error occurred while decoding oaep padding