I wanted to experiment with the -Xmx option in Java and created a simple test program that allocates 1 Mib at the time until it runs out of memory.
import java.util.Vector;
public class MemoryMuncher {
static final int MiB = 1048576;
static final int accellerator = 1;
public static void main(String[] args) {
Vector victor = new Vector();
int i = 1;
try {
while (true) {
byte roger[] = new byte[MiB * accellerator];
victor.add(roger);
Runtime rt = Runtime.getRuntime();
System.out.printf("free: %,6d\t\ttotal: %,6d\t\tallocated: %,6d \n", rt.freeMemory()/MiB, rt.totalMemory()/MiB, i++*accellerator);
}
} catch (OutOfMemoryError e) {
System.out.println(e);
}
}
}
When I run the program with the -Xmx option, I'm noticing a difference in behavior between Java 8 (1.8.0.131) and Java 9 (9.0.1).
Java 8 works close to what I would expect. When I run the program with -Xmx256M, it allocates 233MiB before throwing an OutOfMemoryError.
free: 361 total: 368 allocated: 1
free: 360 total: 368 allocated: 2
...
free: 12 total: 245 allocated: 232
free: 11 total: 245 allocated: 233
java.lang.OutOfMemoryError: Java heap space
However, when I run the same program with Java 9, it only gets about halfway (127 MiB) before I get the exception. This is consistent. If I change the -Xmx to 512M or 1024M, it only gets to half of that amount (255 MiB and 510 MiB respectively). I have no explanation for this behavior.
free: 250 total: 256 allocated: 1
free: 247 total: 256 allocated: 2
...
free: 2 total: 256 allocated: 126
free: 1 total: 256 allocated: 127
java.lang.OutOfMemoryError: Java heap space
I have searched the documentation for any changes in memory management between Java 8 and Java 9, but did not find anything.
Does anyone have any insight why Java 9 would manage/allocate memory differently in some cases from previous Java versions?