Java heap space ошибка декларации

If you keep on allocating & keeping references to object, you will fill up any amount of memory you have.

One option is to do a transparent file close & open when they switch tabs (you only keep a pointer to the file, and when the user switches tab, you close & clean all the objects… it’ll make the file change slower… but…), and maybe keep only 3 or 4 files on memory.

Other thing you should do is, when the user opens a file, load it, and intercept any OutOfMemoryError, then (as it is not possible to open the file) close that file, clean its objects and warn the user that he should close unused files.

Your idea of dynamically extending virtual memory doesn’t solve the issue, for the machine is limited on resources, so you should be carefull & handle memory issues (or at least, be carefull with them).

A couple of hints i’ve seen with memory leaks is:

—> Keep on mind that if you put something into a collection and afterwards forget about it, you still have a strong reference to it, so nullify the collection, clean it or do something with it… if not you will find a memory leak difficult to find.

—> Maybe, using collections with weak references (weakhashmap…) can help with memory issues, but you must be carefull with it, for you might find that the object you look for has been collected.

—> Another idea i’ve found is to develope a persistent collection that stored on database objects least used and transparently loaded. This would probably be the best approach…

If you keep on allocating & keeping references to object, you will fill up any amount of memory you have.

One option is to do a transparent file close & open when they switch tabs (you only keep a pointer to the file, and when the user switches tab, you close & clean all the objects… it’ll make the file change slower… but…), and maybe keep only 3 or 4 files on memory.

Other thing you should do is, when the user opens a file, load it, and intercept any OutOfMemoryError, then (as it is not possible to open the file) close that file, clean its objects and warn the user that he should close unused files.

Your idea of dynamically extending virtual memory doesn’t solve the issue, for the machine is limited on resources, so you should be carefull & handle memory issues (or at least, be carefull with them).

A couple of hints i’ve seen with memory leaks is:

—> Keep on mind that if you put something into a collection and afterwards forget about it, you still have a strong reference to it, so nullify the collection, clean it or do something with it… if not you will find a memory leak difficult to find.

—> Maybe, using collections with weak references (weakhashmap…) can help with memory issues, but you must be carefull with it, for you might find that the object you look for has been collected.

—> Another idea i’ve found is to develope a persistent collection that stored on database objects least used and transparently loaded. This would probably be the best approach…

  1. Upto my knowledge, Heap space is occupied by instance variables only. If this is correct, then why this error occurred after running fine for sometime as space for instance variables are alloted at the time of object creation.

That means you are creating more objects in your application over a period of time continuously. New objects will be stored in heap memory and that’s the reason for growth in heap memory.

Heap not only contains instance variables. It will store all non-primitive data types ( Objects). These objects life time may be short (method block) or long (till the object is referenced in your application)

  1. Is there any way to increase the heap space?

Yes. Have a look at this oracle article for more details.

There are two parameters for setting the heap size:

-Xms:, which sets the initial and minimum heap size

-Xmx:, which sets the maximum heap size

  1. What changes should I made to my program so that It will grab less heap space?

It depends on your application.

  1. Set the maximum heap memory as per your application requirement

  2. Don’t cause memory leaks in your application

  3. If you find memory leaks in your application, find the root cause with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, fix the leaks.

Important notes from oracle article

Cause: The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak.

Possible reasons:

  1. Improper configuration ( not allocating sufficiant memory)
  2. Application is unintentionally holding references to objects and this prevents the objects from being garbage collected
  3. Applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.

On a different note, use better Garbage collection algorithms ( CMS or G1GC)

Have a look at this question for understanding G1GC

  1. Upto my knowledge, Heap space is occupied by instance variables only. If this is correct, then why this error occurred after running fine for sometime as space for instance variables are alloted at the time of object creation.

That means you are creating more objects in your application over a period of time continuously. New objects will be stored in heap memory and that’s the reason for growth in heap memory.

Heap not only contains instance variables. It will store all non-primitive data types ( Objects). These objects life time may be short (method block) or long (till the object is referenced in your application)

  1. Is there any way to increase the heap space?

Yes. Have a look at this oracle article for more details.

There are two parameters for setting the heap size:

-Xms:, which sets the initial and minimum heap size

-Xmx:, which sets the maximum heap size

  1. What changes should I made to my program so that It will grab less heap space?

It depends on your application.

  1. Set the maximum heap memory as per your application requirement

  2. Don’t cause memory leaks in your application

  3. If you find memory leaks in your application, find the root cause with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, fix the leaks.

Important notes from oracle article

Cause: The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak.

Possible reasons:

  1. Improper configuration ( not allocating sufficiant memory)
  2. Application is unintentionally holding references to objects and this prevents the objects from being garbage collected
  3. Applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.

On a different note, use better Garbage collection algorithms ( CMS or G1GC)

Have a look at this question for understanding G1GC

Разбираем частые ошибки ЕГАИС.

Ошибка 1. Проблемы работы с Интернетом, приходит уведомление «Превышено время ожидания». В таком случае, достаточно перезапустить УТМ.  

Ошибка 2. Документы в ЕГАИС медленно обрабатываются или вовсе не загружаются.

Очистите базу УТМ, для этого необходимо остановить службу УТМ. После удалить папку «transportDB» по пути «C:UTMtransporter».

Ошибка 3. Периодически в ответ на исходящую ТТН возвращается тикет с комментарием «Java heap space»

Проверьте в логах УТМ следующие ошибки:

Ошибка проверки RSA сертификата
ERROR ru.centerinform.transport.backbone.schedule.RSACertVerificationJob

Количество выделяемой памяти
java.lang.OutOfMemoryError: Java heap space

Чтобы устранить ошибку в УТМ нужно изменить параметр Java:

  1. Остановите службу транспортного модуля
  2. Сохраните отдельно оригинал «Install.bat»
  3. Удалите службу УТМ «Uninstall.bat»
  4. Измените в Install.bat параметры —JvmMs 500 —JvmMx 1000 (добавлять нужно после —JvmOptions)
  5. После запустите Install.bat, чтобы установить службу с новым параметром. Установка и удаление службы производится из папки C:UTMtransporterbin

Напоминаем, что нужно вовремя обновлять УТМ. Версия вашего УТМ должна быть не ниже 4.2.0 b2470. Версии модуля ниже b2470 могут работать некорректно.

Overview

An out of memory error in Java formally known as java.lang.OutOfMemoryError is a runtime error that occurs when the Java Virtual Machine (JVM) cannot allocate an object in the Java heap memory. In this article, we will be discussing several reasons behind “out of memory” errors in Java and how you can avoid them.

new java job roles

The JVM manages the memory by setting aside a specific size of the heap memory to store the newly allocated objects. All the referenced objects remain active in the heap and keep that memory occupied until their reference is closed. When an object is no longer referenced, it becomes eligible to be removed from the heap by the Garbage collector to free up the occupied heap memory. In certain cases, the Java Garbage Collector (GC) is unable to free up the space required for a new object and the available heap memory is insufficient to support the loading of a Java class, this is when an “out of memory” error occurs in Java.

What causes the out of memory error in Java?

An “out of memory” error in Java is not that common and is a direct indication that something is wrong in the application. For instance, the application code could be referencing large objects for too long that is not required or trying to process large amounts of data at a time. It is even possible that the error could have nothing to do with objects on the heap and the reason behind it like because of third-party libraries used within an application or due to an application server that does not clean up after deployment.

Following are some of the main causes behind the unavailability of heap memory that cause the out of memory error in Java.

· Java heap space error

It is the most common out of memory error in Java where the heap memory fills up while unable to remove any objects.

See the code snippet below where java.lang.OutOfMemoryError is thrown due to insufficient Java heap memory available:

public class OutOfMemoryError01 {
    public static void main(String[] args) {
        Integer[] arr = new Integer[1000 * 1000 * 1000];
    }
}

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:8)

In the above code, an array of integers with a very large size is attempted to be initialized. As the Java heap is insufficient to allocate such a huge array, it will eventually throw a java.lang.OutOfMemoryError: Java heap space error. Initially, it might seem fine but over time, it will result in consuming a lot of Java heap space and when it fills all of the available memory in the heap, Garbage Collection will not be able to clean it as the code would still be in execution and the no memory can be freed.

Another reason for a Java heap space error is the excessive use of finalizers. If a class has a finalize() method, the GC will not clean up any objects of that class, instead, they all will be queued up for finalization at a later stage. If a finalizer thread cannot keep up with the finalization queue because of excessive usage of finalizers, the Java heap will eventually fill up resulting in an “out of memory” error in Java.

Prevention:

Developers need to use the finalize methods only when required and they must monitor all the objects for which finalization would be pending.

· GC Overhead limit exceeded:

This error indicates that the garbage collector is constantly running due to which the program will also be running very slowly. In a scenario where for minimum consecutive 5 garbage collection cycles, if a Java process utilizes almost 98% of its time for garbage collection and could recover less than 2% of the heap memory then a Java Out of Memory Error will be thrown.
This error typically occurs because the newly generated data could barely fit into the Java heap memory having very little free space for new object allocations.

Prevention:

Java developers have the option to set the heap size by themselves. To prevent this error, you must Increase the heap size using the -Xmx attribute when launching the JVM.

· PermGen space error:

JVM separates the memory into different sections. One of the sections is Permanent Generation (PermGen) space. It is used to load the definitions of new classes that are generated at the runtime. The size of all these sections, including the PermGen area, is set at the time of the JVM launch. If you do not set the sizes of every area yourself, platform-specific defaults sizes will be then set. If the Permanent Generation’s area is ever exhausted, it will throw the java.lang.OutOfMemoryError: PermGen space error.

Prevention:

The solution to this out of Memory Error in Java is fairly simple. The application just needs more memory to load all the classes to the PermGen area so just like the solution for GC overhead limit exceeding error, you have to increase the size of the PermGen region at the time of Java launch. To do so, you have to change the application launch configuration and increase or if not used, add the XX:MaxPermSize parameter to your code.

· Out of MetaSpace error:

All the Java class metadata is allocated in native memory (MetaSpace). The amount of MetaSpace memory to be used for class metadata is set by the parameter MaxMetaSpaceSize. When this amount exceeds, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown.

Prevention:

If you have set the MaxMetaSpaceSize on the command line, increasing its size manually can solve the problem. Alternatively, MetaSpace is allocated from the same address spaces as the Java heap memory so by reducing the size of the Java heap, you can automatically make space available for MetaSpace. It should only be done when you have excess free space in the Java heap memory or else you can end up with some other Java out of memory error.

· Out of swap space error:

This error is often occurred due to certain operating system issues, like when the operating system has insufficient swap space or a different process running on the system is consuming a lot of memory resources.

Prevention:

There is no way to prevent this error as it has nothing to do with heap memory or objects allocation. When this error is thrown, the JVM invokes the error handling mechanism for fatal errors. it generates an error log file, which contains all the useful information related to the running threads, processes, and the system at the time of the crash. this log information can be very useful to minimize any loss of data.

How to Catch java.lang.OutOfMemoryError?

As the java.lang.OutOfMemoryError is part of the Throwable class, it can be caught and handled in the application code which is highly recommended. The handling process should include the clean up the resources, logging the last data to later identify the reason behind the failure, and lastly, exit the program properly.

See this code example below:

public class OutOfMemoryError02 {
    public void createArr (int size) {
        try {
            Integer[] myArr = new Integer[size];
        } catch (OutOfMemoryError ex) {
            //creating the Log
            System.err.println("Array size is too large");
            System.err.println("Maximum JVM memory: " + 
Runtime.getRuntime().maxMemory());
        }
    }
    public static void main(String[] args) {
        OutOfMemoryError02 oomee = new OutOfMemoryError02();
        ex.createArr (1000 * 1000 * 1000);
    }
}

In the above code, as the line of code that might cause an out of Memory Error is known, it is handled using a try-catch block. In case, if the error occurs, the reason for the error will be logged that is the large size of the array and the maximum size of the JVM, which will be later helpful for the caller of the method to take the action accordingly.

In case of an out of memory error, this code will exit with the following message:

Array size is too large
Maximum JVM memory: 9835679212

It is also a good option to handle an out of Memory Error in Java when the application needs to stay in a constant state in case of the error. This allows the application to keep running normally if any new objects are not required to be allocated.

See Also: CompletableFuture In Java With Examples

Conclusion

In this article, we have extensively covered everything related to the “out of memory” error in Java. In most cases, you can now easily prevent the error or at least will be able to retrieve the required information after the crashing of the program to identify the reason behind it. Managing errors and exceptions in your code is always challenging but being able to understand and avoid these errors can help you in making your applications stable and robust.

new Java jobs

java.lang.OutOfMemoryError:
Java heap space

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):

OutOfMemoryError: Java heap space

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.

Give me an example

Trivial example

The first example is truly simple – the following Java code tries to allocate an array of 2M integers. When you compile it and launch with 12MB of Java heap space (java -Xmx12m OOM), it fails with the java.lang.OutOfMemoryError: Java heap space message. With 13MB Java heap space the program runs just fine.

class OOM {
  static final int SIZE=2*1024*1024;
  public static void main(String[] a) {
    int[] i = new int[SIZE];
   }
}

Memory leak example

The second and a more realistic example is of a memory leak. In Java, when developers create and use new objects e.g. new Integer(5), they don’t have to allocate memory themselves – this is being taken care of by the Java Virtual Machine (JVM). During the life of the application the JVM periodically checks which objects in memory are still being used and which are not. Unused objects can be discarded and the memory reclaimed and reused again. This process is called Garbage Collection. The corresponding module in JVM taking care of the collection is called the Garbage Collector (GC).

Java’s automatic memory management relies on GC to periodically look for unused objects and remove them. Simplifying a bit we can say that a memory leak in Java is a situation where some objects are no longer used by the application but Garbage Collection fails to recognize it. As a result these unused objects remain in Java heap space indefinitely. This pileup will eventually trigger the java.lang.OutOfMemoryError: Java heap space error.

It is fairly easy to construct a Java program that satisfies the definition of a memory leak:

class KeylessEntry {
 
   static class Key {
      Integer id;
 
      Key(Integer id) {
         this.id = id;
      }
 
      @Override
      public int hashCode() {
         return id.hashCode();
      }
   }
 
   public static void main(String[] args) {
      Map m = new HashMap();
      while (true)
         for (int i = 0; i < 10000; i++)
            if (!m.containsKey(new Key(i)))
               m.put(new Key(i), "Number:" + i);
   }
}

When you execute the above code above you might expect it to run forever without any problems, assuming that the naive caching solution only expands the underlying Map to 10,000 elements, as beyond that all the keys will already be present in the HashMap. However, in reality the elements will keep being added as the Key class does not contain a proper equals() implementation next to its hashCode().

As a result, over time, with the leaking code constantly used, the “cached” results end up consuming a lot of Java heap space. And when the leaked memory fills all of the available memory in the heap region and Garbage Collection is not able to clean it, the java.lang.OutOfMemoryError:Java heap space is thrown.

The solution would be easy – add the implementation for the equals() method similar to the one below and you will be good to go. But before you manage to find the cause, you will definitely have lose some precious brain cells.

@Override
public boolean equals(Object o) {
   boolean response = false;
   if (o instanceof Key) {
      response = (((Key)o).id).equals(this.id);
   }
   return response;
}

What is the solution?

In some cases, the amount of heap you have allocated to your JVM is just not enough to accommodate the needs of your applications running on that JVM. In that case, you should just allocate more heap – see at the end of this chapter for how to achieve that.

In many cases however, providing more Java heap space will not solve the problem. For example, if your application contains a memory leak, adding more heap will just postpone the java.lang.OutOfMemoryError: Java heap space error. Additionally, increasing the amount of Java heap space also tends to increase the length of GC pauses affecting your application’s throughput or latency.

If you wish to solve the underlying problem with the Java heap space instead of masking the symptoms, you need to figure out which part of your code is responsible for allocating the most memory. In other words, you need to answer these questions:

  1. Which objects occupy large portions of heap
  2. where these objects are being allocated in source code

At this point, make sure to clear a couple of days in your calendar (or – see an automated way below the bullet list). Here is a rough process outline that will help you answer the above questions:

  • Get security clearance in order to perform a heap dump from your JVM. “Dumps” are basically snapshots of heap contents that you can analyze. These snapshot can thus contain confidential information, such as passwords, credit card numbers etc, so acquiring such a dump might not even be possible for security reasons.
  • Get the dump at the right moment. Be prepared to get a few dumps, as when taken at a wrong time, heap dumps contain a significant amount of noise and can be practically useless. On the other hand, every heap dump “freezes” the JVM entirely, so don’t take too many of them or your end users start facing performance issues.
  • Find a machine that can load the dump. When your JVM-to-troubleshoot uses for example 8GB of heap, you need a machine with more than 8GB to be able to analyze heap contents. Fire up dump analysis software (we recommend Eclipse MAT, but there are also equally good alternatives available).
  • Detect the paths to GC roots of the biggest consumers of heap. We have covered this activity in a separate post here. It is especially tough for beginners, but the practice will make you understand the structure and navigation mechanics.
  • Next, you need to figure out where in your source code the potentially hazardous large amount of objects is being allocated. If you have good knowledge of your application’s source code you’ll be able to do this in a couple searches.

Alternatively, we suggest Plumbr, the only Java monitoring solution with automatic root cause detection. Among other performance problems it catches all java.lang.OutOfMemoryErrors and automatically hands you the information about the most memory-hungry data structres.

Plumbr takes care of gathering the necessary data behind the scenes – this includes the relevant data about heap usage (only the object layout graph, no actual data), and also some data that you can’t even find in a heap dump. It also does the necessary data processing for you – on the fly, as soon as the JVM encounters an java.lang.OutOfMemoryError. Here is an example java.lang.OutOfMemoryError incident alert from Plumbr:

Plumbr OutOfMemoryError incident alert

Without any additional tooling or analysis you can see:

  • Which objects are consuming the most memory (271 com.example.map.impl.PartitionContainer instances consume 173MB out of 248MB total heap)
  • Where these objects were allocated (most of them allocated in the MetricManagerImpl class, line 304)
  • What is currently referencing these objects (the full reference chain up to GC root)

Equipped with this information you can zoom in to the underlying root cause and make sure the data structures are trimmed down to the levels where they would fit nicely into your memory pools.

However, when your conclusion from memory analysis or from reading the Plumbr report are that memory use is legal and there is nothing to change in the source code, you need to allow your JVM more Java heap space to run properly. In this case, alter your JVM launch configuration and add (or increase the value if present) the following:

-Xmx1024m

The above configuration would give the application 1024MB of Java heap space. You can use g or G for GB, m or M for MB, k or K for KB. For example all of the following are equivalent to saying that the maximum Java heap space is 1GB:


    java -Xmx1073741824 com.mycompany.MyClass
    java -Xmx1048576k com.mycompany.MyClass
    java -Xmx1024m com.mycompany.MyClass
    java -Xmx1g com.mycompany.MyClass

I’m currently running my system against a rather large dataset and am getting the error. ‘Out of memory. Java Heap Space’.

Is there anyway to get around this or is it just a case of the dataset is too large and can’t be used?

trincot's user avatar

trincot

310k35 gold badges240 silver badges282 bronze badges

asked May 7, 2014 at 16:40

user3469624's user avatar

8

In general, you can either

  • give it more memory e.g. increase the maximum heap size, but don’t give it more than about 90% of main memory. BTW the default is 25% of main memory up to 32GB.
  • optimise the code so that it uses less memory, e.g. use a memory profiler. You can use a more efficient data structure or load portions of data into memory at a time.
  • break up the data so it own works on a portion at a time.

answered May 7, 2014 at 16:47

Peter Lawrey's user avatar

Peter LawreyPeter Lawrey

524k77 gold badges749 silver badges1130 bronze badges

If it’s not the dataset that’s eating up memory, it could be that you are not freeing up objects once they are inactive.

This is typically due to keeping references to very large objects or to lots objects laying around long after they are no longer needed. This is most likely references that are static variables, but it can also be references to large temporary variables (e.g., largeStringBuilderobjects) within methods that are still active.

answered May 7, 2014 at 16:54

David R Tribble's user avatar

David R TribbleDavid R Tribble

11.8k5 gold badges42 silver badges52 bronze badges

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

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!!

All the applications that you’re trying to execute require memory. It doesn’t matter if the application was developed using assembly language. Or if you used a low-level programming language like C or a language compiled to a bytecode like Java. Running the application requires memory for the code itself, the variables, and the data that the code processes. Depending on your usage, the memory requirements will vary. Some programs will require very little memory – for example, a simple app designed to process small text files; others will require gigabytes of memory because of the amount of data they process in memory.

In Java, at least initially, you can forget about the memory. You create objects, use them and leave them alone. Eventually, the Java garbage collector (GC) will free the memory occupied by unused objects and release the used memory. However, there is always a limited amount of data you can keep in memory at the same time – the size of the heap.

The heap is the place where the Java Virtual Machine keeps the data needed by the application. The heap is not unlimited – you control it during application start and you can’t keep more objects in memory than it allows. If the heap is full and you create that one more object you may receive an OutOfMemory error.

In this blog post, I’ll tell you what Java OutOfMemory errors are, what causes them and how to deal with them.

A java.lang.OutOfMemoryError means that something is wrong in the application – to be precise there was an issue with a part of application memory. To be more specific than that, we need to dive into the reasons that the Java Virtual Machine can go out of memory, and each has a different cause.

Java Heap Space

Java Heap space is one of the most common errors when it comes to memory handling in the Java Virtual Machine world. This error means that you tried to keep too much data on the heap of the JVM process and there is not enough memory to create new objects, and that the garbage collector can’t collect enough garbage. This can happen for various reasons – for example, you may try to load files that are too large into the application memory or you keep the references to the objects even though you don’t need the data.

Basically, the java.lang.OutOfMemoryError Java heap space tells that the heap of your application is not large enough or you are doing something wrong, or you have an old, good Java memory leak.

Here’s an example that illustrates the Java heap space problem:

public class JavaHeapSpace {
  public static void main(String[] args) throws Exception {
    String[] array = new String[100000 * 100000];
  }
}

The code tries to create an array of String objects that is quite large. And that’s it. With the default settings for the memory size, you should see the following result when executing the above code:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
  at memory.JavaHeapSpace.main(JavaHeapSpace.java:5)

And the result is simple – there is just not enough memory on the heap to assign the array, and thus the JVM throws an error informing us about that.

How to fix it: In some cases, to mitigate the problem, it is enough to increase the maximum heap size by adding the -Xmx to your JVM application startup settings and setting it to a larger value. For example, to increase the maximum heap size to 8GB, you would add the -Xmx8g parameter to your JVM application start parameters. However, if you have a memory leak you will eventually see the error appearing again. This means that you need to go through the application code and look for places where potential memory issues can happen. Tools like Java profilers and the good, old heap dump will help you with that.

GC Overhead Limit

The GC Overhead Limit is exactly what its name suggests – a problem with the Java Virtual Machine garbage collector not being able to reclaim memory. You will see the java.lang.OutOfMemoryError: GC overhead limit exceeded if the Java Virtual Machine spends more than 98% of its time in the garbage collection, for 5 consecutive garbage collections and can reclaim less than 2% of the heap.

When using older Java versions that were using the older implementations of the garbage collection (like Java 8), you can easily simulate the GC Overhead exception by running a code similar to the following:

public class GCOverhead {
  public static void main(String[] args) throws Exception {
    Map<Long, Long> map = new HashMap<>();
    for (long i = 0l; i < Long.MAX_VALUE; i++) {
      map.put(i, i);
    }
  }
}

When run with a small heap, like 25MB you would get an exception like this:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
        at java.base/java.lang.Long.valueOf(Long.java:1211)
        at memory.GCOverhead.main(GCOverhead.java:10)

That means that the heap is almost full and the garbage collector spent at least 5 consecutive garbage collections removing less than 2% of the assigned objects.

How to fix it: The possible solution to such an error is increasing the heap by adding the -Xmx to your JVM application startup settings and setting it to a larger value than you are currently using.

Array Size Limits

One of the errors that you may encounter is the java.lang.OutOfMemoryError: Requested array size exceeds VM limit, which points out that the size of the array that you’re trying to keep in memory is larger than the Integer.MAX_INT or that you’re trying to have an array larger than your heap size.

How to fix it: If your array is larger than your heap size, you can try increasing the heap size. If you are trying to put more than the 2^31-1 entries into a single array, you will need to modify your code to avoid such situations.

Number of Thread Issues

The operating system has limits when it comes to the number of threads you can run inside a single application. When you see a java.lang.OutOfMemoryError: unable to create native thread error being thrown by the Java Virtual Machine running your code, you can be sure that you hit the limit or your operating system runs out of resources to create a new thread. Basically, a new thread was not created on the operating system level and the error happened in the Java Native Interface or in the native method itself.

To illustrate the issue with the creation of threads let’s create a code that continuously creates threads and puts them to sleep. For example like this:

public class ThreadsLimits {
  public static void main(String[] args) throws Exception {
    while (true) {
      new Thread(
          new Runnable() {
            @Override
            public void run() {
              try {
                Thread.sleep(1000 * 60 * 60 * 24);
              } catch (Exception ex) {}
            }
          }
      ).start();
    }
  }
}

Right after you run the above code, you can expect an exception thrown:

[0.420s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 4k, detached.
Exception in thread "main" java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached
  at java.base/java.lang.Thread.start0(Native Method)
  at java.base/java.lang.Thread.start(Thread.java:802)
  at memory.ThreadsLimits.main(ThreadsLimits.java:15)

We can clearly see that our Java code exhausted the operating system limits and couldn’t create more threads.

To diagnose the issue, we suggest referring to the appropriate section of the Java documentation. For example, Java 17 documentation includes a section called Troubleshooting Tools Based on the Operating System, which mentions tools that can help you find the problem.

PermGen Issues

The PermGen or Permanent Generation is a special place in the Java heap that the Java Virtual Machine uses to keep track of all the loaded classes metadata, static methods, references to static objects, and primitive variables. The PermGen was removed with the release of Java 8, so at this point, you’ll probably never hit the issue with it.

The problem with PermGen was its limited default size – 64MB in 32-bit Java Virtual Machine version and up to 82MB in the 64-bit version of the JVM. This was problematic because if your application contained a lot of classes, static methods, and references to static objects, you could easily get into issues with too small PermGen space.

How to fix it: If you ever encounter the java.lang.OutOfMemoryError: PermGen space error you can start by increasing the size of the PermGen space by including the -XX:PermSize and -XX:MaxPermSize JVM parameters.

Metaspace Issues

With the removal of the PermGen space, the classes metadata now lives in the native space. The space that keeps the classes metadata is now called Metaspace and is part of the Java Virtual Machine heap. However, the region is still limited and can be exhausted if you have a lot of classes.

How to fix it: The problems with the Metaspace region are signaled by the Java Virtual Machine when a java.lang.OutOfMemoryError: Metaspace error is thrown. To mitigate the issue, you can increase the size of the Metaspace by adding the -XX:MaxMetaspaceSize flag to startup parameters of your Java application. For example, to set the Metaspace region size to 128M, you would add the following parameter: -XX:MaxMetaspaceSize=128m.

Out of swap

Your operating system uses the swap space as the secondary memory to handle the memory management scheme’s paging process. When the native memory–both the RAM and the swap–is close to exhaustion, the Java Virtual Machine may not have enough space to create new objects. This may happen for various reasons – your system may be overloaded, other applications may be heavy memory users and are exhausting the resources. In this case the JVM will throw the java.lang.OutOfMemoryError: Out of swap space error, which means that the reason is a problem on the operating system side.

How to fix it: The exact exception stack is usually helpful for mitigatin the error, as it will include the amount of memory that the JVM tried to allocate and the code which did that. When this error occurs, you can expect your Java Virtual Machine to create a file with a detailed description of what happened. You may also want to check your operating system swap settings and increase it if that is too low. At the same time, you need to verify if there are other heavy memory consumers running on the same machine as your application.

How to Catch java.lang.OutOfMemoryError Exceptions

Java has the option to catch exceptions and handle them gracefully. For example, you can catch the FileNotFoundException that can be thrown when trying to work with a file that doesn’t exist. The same can be done with the OutOfMemoryError – you can catch it, but it doesn’t make much sense, at least in most cases. As the developers, we usually can’t do much about the lack of memory in our application. But maybe your specific use-case is such that you would like to do that.

To catch the OutOfMemoryError you just need to surround the code that you expect to cause memory issues with the try-catch block, just like this:

public class JavaHeapSpace {
  public static void main(String[] args) throws Exception {
    try {
      String[] array = new String[100000 * 100000];
    } catch (OutOfMemoryError oom) {
      System.out.println("OutOfMemory Error appeared");
    }
  }
}

The execution of the above code, instead of resulting in the OutOfMemoryError will result in printing the following:

OutOfMemory Error appeared

In such a case, you can try recovering from that error, but that is highly use-case dependent. The best solution is to analyze the places where you’re trying to catch the OutOfMemoryError. Definitely avoid catching the mentioned error in the main method where you just start the whole execution. If you don’t know everything about exception handling in Java read our blog post to learn more about how to deal with OutOfMemoryError and other types of Java errors.

Monitor and Analyze Java OutOfMemoryError with Sematext

handle java outofmemoryerror

To ensure a healthy environment for your business process you need to be sure you will not miss any of the errors that can be caused by memory issues when running your Java applications. This means that you need to pay close attention to the logs produced by your Java applications and set up alerting on the relevant events – the OutOfMemoryError ones. You can achieve all of this by using Sematext Logs – an intelligent and easy to use logs centralization solution allowing you to get all the needed information in one place, create alerts and be proactive when dealing with memory issues.

You can read more about Sematext Logs and how it compares with similar solutions in our blog posts about the best log management software, log analysis tools, and cloud logging services available today. Or, if you’d like, check out the short video below to get more familiar with Sematext Logs and how they can help you.

Conclusion

Each memory-related error in Java is different and the approach that we need to take to fix it is different. The first and the most important thing is understanding. To know what needs to be fixed, we need to understand what kind of error happened, when it happened, and finally, why it happened. This information is crucial to take proper reaction and fix the underlying issue that is the root cause of the error.

That is where log management tools, like the Sematext Logs come into play. Having a place where you can see all your exceptions and analyze them is priceless. Sematext Logs is a part of Sematext Cloud, an all-in-one observability solution with Java monitoring integration and JVM Garbage Collector logging capabilities. All of that combined gives you a single platform that allows you to correlate all the necessary metrics. This provides you with a full view of the problem and helps you get to its root cause fast and efficiently. There’s a 14-day free trial available for you to try its features, so give it a try!

Start Free Trial


Понравилась статья? Поделить с друзьями:
  • Jane is an painter исправьте ошибки
  • Jade empire ошибка загрузки игры
  • J 0511 принтер kyocera ошибка
  • Iп5p ошибка фольксваген поло седан
  • Iwse 6105 indesit ошибка f02