0

I am little surprised to see why on my machine, the maximum size of an array is Integer.MAX_VALUE/7
I know that the arrays are indexed by integers, and so the array size cannot be greater than Integer.MAX_VALUE. I also read some stackoverflow discussions where I found that it varies on the JVM, and some(5-8 bites) are used by JVM.
In that case also, the maximum values should be Integer.MAX_VALUE-8.

Any value in between Integer.MAX_VALUE-2 and Integer.MAX_VALUE/7 gives me the error: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

int[] arr = new int[Integer.MAX_VALUE/7];

This is the largest value I can assign to array on my machine. Are specific reasons for this?

Update: I am running the code from eclipse in which the default heap size is 1024Mb. Below are the more details from my environment:

System.out.println(Runtime.getRuntime().totalMemory()/(1024*3));
System.out.println(Runtime.getRuntime().freeMemory()/(1024*3));
System.out.println(Runtime.getRuntime().maxMemory()/(1024*3));

give the output:

40618
40195
594773
6
  • 3
    What is your maximum heap size set to? Commented Jan 20, 2018 at 19:36
  • 1
    stackoverflow.com/questions/3038392/… Commented Jan 20, 2018 at 19:41
  • @OliverCharlesworth updated the details. Commented Jan 20, 2018 at 20:18
  • 1
    @cloudwalker I have already mentioned that link in my question. And I came to create a new question only when I didn't find that link helpful. Commented Jan 20, 2018 at 20:19
  • 3
    Dear downvoters, it would be very soothing to my mind if anyone could explain me for your downvotes!!!! Commented Jan 20, 2018 at 20:20

1 Answer 1

2

As mentioned already by cloudworker, the real limits for array are explained here: Do Java arrays have a maximum size?

In your case 1GB is just not enough heap space for array that huge.

I do not know what exact processes are run in JVM, but from what I am able to count:

Integer.MAX_VALUE= ~2 billions
int = 4bytes
2billions*4bytes=8billions bytes = 8GB memory

With 1GB heapspace you should be able to have ~ /8 of MAX_VALUE. (I think that reason that you can actually get more than /8 is some optimization in JVM)

Sign up to request clarification or add additional context in comments.

1 Comment

I ran into a situation where I need to store around 300mb xml file. Since String is backed by a char[] only, and the maximum value a char[] can consume would be ~2billion * 2byte = 4GB. Will it be a bad practice to store such large file into String instance?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.