Java how to get max size of byte array that will fit vm limit
How can I find the maximum size of a byte array that will not exceed the VM limit?
What I have tried:
int size = Integer.MAX_VALUE;
byte[] request = new byte[size];
But then I get the error: Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
The backstory is my packet proxy which is missing a portion of the packet because I don’t know what the maximum memory size I can use.
Thank!
You can find the answer to your question yourself with something like
long maxByteArraySize() {
long size = Integer.MAX_VALUE;
while(--size > 0) try {
new byte[size];
break;
} catch(Throwable t) {}
return size;
}
Also note that you can increase the amount of memory available to the jvm with a flag -Xmx
for example: java -Xmx4g MyClass
will probably allow you to allocate a (much) larger array than you get by default.
(Not that I think what you are trying to do is actually a great idea ...)
source to share
Mostly arrays
viewed as objects in java. And objects are stored on heap memory
. It doesn't matter if your objects are local objects, but only its references are stored in stack memory
. You can find max heap size
like this: -
java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize
And take roughly a smaller size array.
source to share
Allocating the maximum amount in the array is unlikely to reach the VM limit.
However, if memory is a constraint, you can use the free runtime memory to calculate it.
int maxSize = Math.min(Integer.MAX_VALUE - 8, Runtime.getRuntime().freeMemory());
This assumes you are using an array byte
(which you are), however for objects you will need to split the maximum memory by the size of the object, including the object header (4 and 8 bytes for 32/64-bit JVMs respectively).
source to share