특정 크기의 메모리를 사용해야하는 프로그램을 작성하려고합니다. 궁금해하는 문제는 실제로 힙에 여유 공간이있을 때 outOfMemory
예외가 발생한다는 것입니다.전체 메모리를 사용할 수 없음
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");
//100mb
byte b[] = new byte[104857600];
v.add(b);
}
} else {
//100mb
byte b[] = new byte[104857600];
v.add(b);
System.out.println("Added 100 mb");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
는 IT 시작 명령 :
java -Xmx4096m MemoryEater1 3000
출력 :
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)
음 최대 메모리 및 총 메모리의 차이는 여기
는 코드 774 메가 바이트, 100 메가 바이트를 더 소비하기에 충분해야하지만, 여전히 오류가 있으며, 심지어 기계 resourc 충분히 충분하다 :[[email protected] ~]$ free -m
total used free shared buffers cached
Mem: 15950 3447 12502 0 210 2389
-/+ buffers/cache: 847 15102
Swap: 4031 1759218603 8941
왜 그럴 수 있습니까?
사용 가능한 메모리가 100MB 미만인지 확인 했습니까? – Stephan
큰 배열을 할당 할 때, 방이 남아있을지라도 JVM이 커다란 연속 블록을 찾지 못할 위험이 항상 있습니다. –
@Stephan'totalMemory'가 이미'maxMemory'로 확장 된 경우에만 관련이 있습니다. –