简体   繁体   中英

Java how to get max byte array size that will fit the vm limit

How can I find the maximum byte array size that will not exceed the VM limit?

What I tried is:

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 keeps missing parts of a packet because I don't know what the max memory size I can use is.

Thanks!

You can find out 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 -Xmx flag, eg: java -Xmx4g MyClass will probably let you allocate (a lot) larger array than you are getting by default.

(Not that I think that what you are trying to do is actually a great idea ...)

Well Integer.MAX_VALUE is 2,147,483,647 ; you can determine how much memory is free with

System.out.println(Runtime.getRuntime().freeMemory());

But I wouldn't try and allocate all of it to a byte[] .

Basically arrays are considered to be objects in java. And objects are stored on heap memory . It doesn't matter whether your objects are local objects but only its references are stored in stack memory . You can find the max heap size by following :-

java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize

And approximately take less size array.

Allocating the maximum amount in an array will be unlikely to reach the VM limit.

However, if memory is a limitation, you can use the runtime's free memory to calculate it.

int maxSize = Math.min(Integer.MAX_VALUE - 8, Runtime.getRuntime().freeMemory());

This assumes you are using a byte array (which you are), however for objects, you'd have to divide the max memory by the object size, which includes the object header (4 and 8 bytes for 32/64 bit JVMs respectively).

See https://stackoverflow.com/a/8381338/3308999

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM