Quickly allocate 1 GB of memory:
byte[][] memoryWaster = new byte[1024][1_048_576];
See last test run below for successful allocation of 16 GB of memory.
Test program
Runtime runtime = Runtime.getRuntime();
System.out.printf("total: %11d max: %d%n", runtime.totalMemory(), runtime.maxMemory());
System.out.printf("used: %11d%n", runtime.totalMemory() - runtime.freeMemory());
System.gc();
System.out.printf("gc: %11d%n", runtime.totalMemory() - runtime.freeMemory());
byte[][] memoryWaster = new byte[1024][1_048_576];
memoryWaster[0][0] = 2; // prevent unused warning
System.out.printf("new[]: %11d%n", runtime.totalMemory() - runtime.freeMemory());
System.gc();
System.out.printf("gc: %11d%n", runtime.totalMemory() - runtime.freeMemory());
memoryWaster = null;
System.out.printf("null: %11d%n", runtime.totalMemory() - runtime.freeMemory());
System.gc();
System.out.printf("gc: %11d%n", runtime.totalMemory() - runtime.freeMemory());
Output (Java 8, 32-bit):
// Java 1.8.0_51, 32-bit, no -Xmx given
total: 16252928 max: 259522560
used: 543288
gc: 349296
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at test.Test.main(Test.java:11)
// Java 1.8.0_51, 32-bit, -Xmx1200m
total: 16252928 max: 1216348160
used: 543288
gc: 349296
new[]: 1078435312
gc: 1078382592
null: 1078382592
gc: 15711288
// Java 1.8.0_51, 64-bit, no -Xmx given, 32 GB machine
total: 514850816 max: 7618953216
used: 5389872
gc: 2981048
new[]: 1074961632
gc: 1081175720
null: 1081175720
gc: 13027424
// Java 1.8.0_51, 64-bit, -Xmx1200m
total: 514850816 max: 1118830592
used: 5389872
gc: 2981048
new[]: 1077948560
gc: 1078944096
null: 1078944096
gc: 3501136
// Java 1.8.0_51, 64-bit, -Xmx20g, new byte[16384][1_048_576]
total: 514850816 max: 19088801792
used: 5389872
gc: 2981048
new[]: 17205604928
gc: 17205604928
null: 17205604928
gc: 26186032
2
solved best Java code to control big heap memeory used (like 1G) [closed]