There is a limit on the declaration of maximum array size in java. So whenever we face the OutOfMemoryError i.e, Requested array size exceeds VM limit it means that the program is trying to allocate a particular size to an array that is larger than the size supported by the virtual machine.
Cause of Error
The value of maximum positive integer in java is 2^31 – 1 = 2,147,483,647. Now it depends on the specifications of the different operating systems whether it allows creating an array of size Integer.MAX_VALUE – 1 or Integer.MAX_VALUE – 2 or much lesser than both of these. The need to create such large arrays rarely happens so many programmers don’t know about the cause of OutOfMemoryError.
You can run some programs to find the maximum array limit for your operating system.
Example Code:
import java.io.* ; public class thejavaprogrammer { public static void main(String[] args) { for(int i=4 ; i>=0 ;i--) { try { int arr[]=new int[Integer.MAX_VALUE-i]; }catch (Throwable ex){ ex.printStackTrace(); } } } }
Output:
java.lang.OutOfMemoryError: Java heap space at thejavaprogrammer.main(thejavaprogrammer.java:9) java.lang.OutOfMemoryError: Java heap space at thejavaprogrammer.main(thejavaprogrammer.java:9) java.lang.OutOfMemoryError: Java heap space java.lang.OutOfMemoryError: Requested array size exceeds VM limit java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Code Explanation:
We are executing a for loop which starts at i=4 & ends at i=0. Each time we will use try and catch the exception. If the array of Integer.MAX_VALUE-i is possible to create then the try block is executed otherwise we catch the error and print it.
From the output, you can see that when the values of i are equal to 4, 3, and 2 then it shows “Java heap space error”. It basically means that the required array size is more than the default heap size of the system.
If the value of i is equal to 1 or 0 then the output is “ Requested array size exceeds the VM limit.
Solution of Error
If you are getting “Java heap space error” then first of all check is it compulsory to use the array of this size. Possibly try to break it into several parts and complete the work in several batches.
In case of using the array of the same size compulsorily, we can increase the heap size as required.
If you are getting “Requested array size exceeds the VM limit” then it simply means that the size of the array allocated is more than your machine can allow. So it is not possible to create an array of such a large size. You can break the large dataset into several batches and write the program by still using standard java utilities.
Conclusion
In this blog, we saw the reasons for the “Out Of Memory” error in java and tried to implement appropriate solutions for them. Please do comment below if you are still having any doubts.