Try garbage collecting before creating the test array with runtime.gc()
.
If you aren't creating a brand new JVM each time you could be getting bit by having different start states.
Mine works for values > 1. 1.25 for example. Then I get a 'heap space' exception.
Here, perhaps you want 'maxMemory()' instead.
public class Mem2 {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
runtime.gc();
long freeMemory = runtime.freeMemory();
// This is some arbitary factor that should work <= 1
double factor = 1.29;
int size = (int) (factor * freeMemory);
System.out.println(" freememory is " + freeMemory);
System.out.println(" size is " + size);
System.out.println("the total memory is " + runtime.totalMemory());
System.out.println(" the max memory is " + runtime.maxMemory());
byte[] testArray = new byte[size];
}
}
Output:
freememory is 84466864
size is 108962254
the total memory is 85000192
the max memory is 129957888
Process finished with exit code 0
So there seems to be about 20M I can't account for.
I think totalMemory() is the amount of memory currently allocated by the JVM, freeMemory() is how much of this has been uses, and maxMemory() is the hard limit.
You can see the interplay between totalMemory()
and freememory()
with this variant on your code.
public class Mem3 {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
for (int i = 0; true; i++) {
runtime.gc();
int size = i * 10000000;
System.out.println(" i is " + i);
System.out.println(" size is " + size);
System.out.println("b freememory is " + runtime.freeMemory());
System.out.println("b the total memory is " + runtime.totalMemory());
System.out.println("b the max memory is " + runtime.maxMemory());
byte[] testArray = new byte[size];
System.out.println(" array " + testArray.length);
System.out.println("a freememory is " + runtime.freeMemory());
System.out.println("a the total memory is " + runtime.totalMemory());
System.out.println("a the max memory is " + runtime.maxMemory());
System.out.println(" ");
}
}
}
If you run that and look at the before and after values, you can see what's going on. Note what happens between interations 6 and 7:
i is 6
size is 60000000
b freememory is 84300496
b the total memory is 85000192
b the max memory is 129957888
array 60000000
a freememory is 24300472
a the total memory is 85000192
a the max memory is 129957888
i is 7
size is 70000000
b freememory is 84300496
b the total memory is 85000192
b the max memory is 129957888
array 70000000
a freememory is 59258168
a the total memory is 129957888
a the max memory is 129957888
We see in 6 that after the allocation of 60M, there are about 24M remaining. In 7, however, we've exceeded a threshold. More memory has been allocated (note totalMemory) and freeMemory is now just under 60M.