I am trying to write a program that should consume memory of a certain size. I am wondering that I get an outOfMemory exception when there really is free space on the heap.
Here is the code:
import java.util.Vector; import java.lang.*; public class MemoryEater1 { public static void main(String[] args) { try { long mb = Long.valueOf(args[0]); Vector v = new Vector(); Runtime rt = Runtime.getRuntime(); while (true) { if (v.size() > 0) { if (((long) v.size())*100 < mb) { System.out.println("total memory: " + rt.totalMemory()/1024/1024); System.out.println("max memory: " + rt.maxMemory()/1024/1024); System.out.println("free memory: " + rt.freeMemory()/1024/1024); System.out.println("Trying to add 100 mb");
Command to run:
java -Xmx4096m MemoryEater1 3000
And the conclusion:
total memory: 2867 max memory: 3641 free memory: 59 Trying to add 100 mb Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at MemoryEater1.main(MemoryEater1.java:18)
Well, the difference between maximum memory and shared memory is 774 MB, which should be enough to consume 100 MB more, but still there is an error, and even sufficient machine resources:
[ user@machine ~]$ free -m total used free shared buffers cached Mem: 15950 3447 12502 0 210 2389 -/+ buffers/cache: 847 15102 Swap: 4031 1759218603 8941
Why could this be?
source share