简体   繁体   中英

Why JVM doesn't throw out of memory error even if the memory reached the maximum heap size?

I am running a Java programming which creates more objects in memory inside a while loop. I set the maximum heap size as 10MB. I am watching task manager, the JVM runs even after 10 MB. I am expecting out of memory. But it is not throwing , it is keep printing a statement in while loop.

java -Xmx10m Main

public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        String s1 = "01011001100100";
        char[] charArray = s1.toCharArray();
        int index = 0;
        StringBuffer result = new StringBuffer();
        StringBuffer temp = new StringBuffer();
        
        while(index < charArray.length){
            System.out.println(index+" : "+charArray[index]);
            if(charArray[index] == '1' && charArray[index--] == '0'){ ***--- This is buggy code***
                result.append(1);
            } else {
                temp.append(charArray[index]);
            }
            index++;
        }
        System.out.println("Result >"+result);
    }
}

Thanks

Why JVM doesn't throw out of memory error even if the memory reached the maximum heap size?

Why?

Because the -xmx parameter sets the maximum Java heap size, NOT the total memory size for the Java process. A lot of a JVM's memory utilization is not in the heap. This includes:

  • memory used to hold the code for the java executable and shared native libraries
  • memory used for the native heap; eg malloc calls in native code
  • memory used for metaspace
  • memory used for thread stacks
  • memory used when a file is mapped into memory
  • and so on.

Some of the above can lead to an OOME (for example, failure to allocate a new thread stack), but the heap size that you set with -xmx does not limit them in any way.

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