OutOfMemoryError JVM에 의해 발생 , JVM에 사용 가능한 메모리가 충분하지 않은 경우 할당합니다. 메모리 부족 오류 E에 해당 오류 카테고리 예외 클래스 계층.
OutOfMemoryError를 생성하려면
- 큰 메모리 청크를 할당하여 힙 메모리 저장소를 고갈시킵니다. .
- 메모리를 계속 할당하고 JVM에 할당할 메모리가 충분하지 않을 때 지점에 도달하고 OutOfMemoryError 던져질 것입니다.
- OutOfMemory 오류를 기록할 수 있습니다.
예
public class OutOfMemoryErrorDemo {
public static void main(String[] args) throws Exception {
int dummyArraySize = 15;
System.out.println("Max JVM memory: " + Runtime.getRuntime().maxMemory());
long memoryConsumed = 0;
try {
long[] memoryAllocated = null;
for(int loop = 0; loop < Integer.MAX_VALUE; loop++) {
memoryAllocated = new long[dummyArraySize];
memoryAllocated[0] = 0;
memoryConsumed += dummyArraySize * Long.SIZE;
System.out.println("Memory Consumed till now: " + memoryConsumed);
dummyArraySize *= dummyArraySize * 2;
Thread.sleep(500);
}
} catch (OutOfMemoryError outofMemory) {
System.out.println("Catching out of memory error");
//Log the information, so that we can generate the statistics
throw outofMemory;
}
}
} 출력
Max JVM memory: 119537664 Memory Consumed till now: 960 Memory Consumed till now: 29760 Memory Consumed till now: 25949760 Catching out of memory error Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:9)
OOM의 근본 원인을 찾는 단계
1단계:OutOfMemoryError에서 힙 덤프 생성
VM 인수 -XX:+HeapDumpOnOutOfMemoryError로 애플리케이션 시작 . 이것은 JVM에 힙 덤프를 생성하도록 지시합니다. OOM 발생 시
$ java -XX:+HeapDumpOnOutOfMemoryError ...
2단계:문제 재현
문제를 재현할 수 없는 경우 개발 환경에서 , 프로덕션 을 사용해야 할 수도 있습니다. 환경 . 문제를 재현하고 애플리케이션에서 OOM을 발생시키면 힙 덤프 파일이 생성됩니다.
3단계:힙 덤프 파일을 사용하여 문제 조사
VisualVM 사용 힙 덤프 파일 읽기 문제를 진단합니다. 비주얼 VM JDK_HOME/bin/jvisualvm에 있는 프로그램입니다. . 힙 덤프 파일 응용 프로그램의 메모리 사용량에 대한 모든 정보가 있습니다.