Try мусора сбор перед созданием тестового массива с runtime.gc()
.
Если вы не создаете совершенно новый JVM каждый раз, когда можете получить бит, имея разные начальные состояния.
Шахта работает для значений> 1. 1.25, например. Тогда я получаю исключение «кучного пространства».
Здесь, возможно, вы хотите вместо этого «maxMemory()».
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];
}
}
Выход:
freememory is 84466864
size is 108962254
the total memory is 85000192
the max memory is 129957888
Process finished with exit code 0
Так что, кажется, о 20М я не могу объяснить.
Я думаю, что totalMemory() - это объем памяти, выделенный в настоящее время JVM, freeMemory() - это то, что из этого было использовано, а maxMemory() - это жесткий предел.
Вы можете увидеть взаимосвязь между totalMemory()
и freememory()
с этим вариантом на код.
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(" ");
}
}
}
Если вы запустите это и посмотрите на значения до и после, вы увидите, что происходит. Обратите внимание, что происходит между interations 6 и 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
Мы видим в 6, что после выделения 60M, есть около 24М осталось. Однако в 7 мы превысили порог. Было выделено больше памяти (примечание totalMemory), а freeMemory сейчас чуть меньше 60M.
Из любопытства, каковы шансы, что вы переполняете 'int', когда вы бросаете и умножаете? –
Хотелось бы, чтобы все было так просто. –
Одной из причин, почему это может быть неудачно для больших значений 'factor', является то, что вы запрашиваете смежные байты в массиве. Возможно, вы сможете выделить более полную память, используя меньшие куски. – msandiford