This SO answer clarifies a few things about the -Xmx JVM -Xmx . Trying to experiment, I did the following:
import java.util.List; import java.util.ArrayList; public class FooMain { private static String memoryMsg() { return String.format("%s. %s. %s" , String.format("total memory is: [%d]",Runtime.getRuntime().totalMemory()) , String.format("free memory is: [%d]",Runtime.getRuntime().freeMemory()) , String.format("max memory is: [%d]",Runtime.getRuntime().maxMemory())); } public static void main(String args[]) { String msg = null; try { System.out.println(memoryMsg()); List<Object> xs = new ArrayList<>(); int i = 0 ; while (true) { xs.add(new byte[1000]); msg = String.format("%d 1k arrays added.\n%s.\n" , ++i , memoryMsg()); } } finally { System.out.printf(msg); } } }
Compile it with javac FooMain.java . When I run it with a maximum heap size of 5 million bytes, I get:
java -Xmx5000000 FooMain total memory is: [5242880]. free memory is: [4901096]. max memory is: [5767168] 4878 1k arrays added. total memory is: [5767168]. free memory is: [543288]. max memory is: [5767168]. Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded at java.lang.String.toCharArray(String.java:2748) at java.util.Formatter$FormatSpecifier.print(Formatter.java:3048) at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2744) at java.util.Formatter$FormatSpecifier.print(Formatter.java:2702) at java.util.Formatter.format(Formatter.java:2488) at java.util.Formatter.format(Formatter.java:2423) at java.lang.String.format(String.java:2792) at FooMain.memoryMsg(FooMain.java:7) at FooMain.main(FooMain.java:21)
As long as the numbers are close enough, they don't seem very accurate (with the exception of total memory at the end, reaching exactly max memory ). In particular, 5368 arrays of 1000 bytes each should occupy more than 5,000,000 or even 5,242,880 bytes. How should these numbers be understood?
This is the java I am using:
java version "1.7.0_80" Java(TM) SE Runtime Environment (build 1.7.0_80-b15) Java HotSpot(TM) Server VM (build 24.80-b11, mixed mode)
java java-7
Marcus junius brutus
source share