Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java heap memory allocation limits

Tags:

java

memory

I've written the following test to check maximum available heap memory:

import java.util.*;
public class Memory {
    public static void main(String[] args) {
        long maxMB = Runtime.getRuntime().maxMemory() / 1048576L;
        System.out.println("Maximum memory is " + maxMB + " MB.");
        ArrayList<byte[]> allocated = new ArrayList<>();
        try {
            while (true)
                allocated.add(new byte[1024*1024]);
        } catch (OutOfMemoryError e) {
            System.out.println("allocated " + allocated.size() + " MB before running out of memory.");
        }
    }
}

However, when I test this, it appears that only half of the "available" memory can actually be allocated:

$ java -Xmx512m Memory 
Maximum memory is 512 MB.
allocated 255 MB before running out of memory.
$ java -Xmx1024m Memory 
Maximum memory is 1024 MB.
allocated 511 MB before running out of memory.

Anyone know why this would be the case?

like image 880
Henning Koehler Avatar asked Oct 02 '21 04:10

Henning Koehler


People also ask

What is Max heap size in 64 bit JVM?

For 64 bit platforms and Java stacks in general, the recommended Maximum Heap range for WebSphere Application Server, would be between (4096M - 8192M) or (4G - 8G).

What is the maximum heap size?

Maximum heap size is 1/4th of the computer's physical memory or 1 GB (whichever is smaller) by default. The maximum heap size can be overridden using -Xmx.

Does Java have a memory limit?

This is just the heap. Sorry, didn't read your question fully at first. You need to run the JVM with the following command line argument. That will allow a max of 1GB of memory for the JVM.

How much heap memory is too much?

In these FAQs, you'll see that SOracle says that on 32-bit Windows, you'll be limited to a max heap size of 1.4 to 1.6 GB. I never was able to get it stable that high, and I suspect you're running a similar configuration.


1 Answers

I believe what happens is that the memory manager tries to align the chunks at the next available 1MB boundary. But as the 1MB arrays actually take up slightly more than 1MB (for storing length and something else), they get arranged with a gap of almost 1MB between them. When reducing the block size by 16 bytes, they suddenly use up the whole memory again.

like image 141
Henning Koehler Avatar answered Oct 09 '22 03:10

Henning Koehler