본문 바로가기

Language/자바

[Java] Java Memory Leaks et al. [2. Act]

https://blog.codecentric.de/en/2011/03/java-memory-leaks-et-al/ 참조



Purpose

* 자바 어플리케이션에서 어떻게 OOM 이 발생하는지 자세하게 분석 


Desc

* 자바 명세에 따르면, 모든 힙은 GC를 가지고 있다. 그래서 전체 메모리는 live objects 로 가득차 있음.

  

  In Java objects get generated on the heap and live on as long as they are referenced.

  Java 객체에서 힙에 생성되어 참조되는 한 계속 살아납니다.

  

  GC는 GC단계에서 객체가 여전히 참조가 걸려있는지 체크한다. 그리고 'garbage' 라고 표시하고 후에 clean 한다. 이것이

  더 이상 안쓰일 때. 


GC Roots

* GC Roots 는 incoming reference 를 안가지고 있으며, 객체를 살아있게 참조하도록 유지해야하는 책임이 있다.

* 하나의 객체가 GC root 에 직접적으로나 간접적으로 도달할 수 없다면, 이것은 unreachable 로 표시되고

  GC 대상이 된다. 

* GC roots 3가지 종류

 - 한 스레드의 스택의 임시적인 변수

 - 로드된 클래스의 고정 변수들

 - JNI 로부터의 특별한 native 참조


* Example

public class MyFrame extends javax.swing.JFrame {
 
  // reachable via Classloader as soon class is loaded
  public static final ArrayList STATIC = new ArrayList();
 
  // as long as the JFrame is not dispose()'d,
  // it is reachable via a native window
  private final ArrayList jni = new ArrayList()
 
  // while this method is executing parameter is kept reachable,
  // even if it is not used
  private void myMethod(ArrayList parameter) {
 
    // while this method is running, this list is reachable from the stack
    ArrayList local = new ArrayList();
  }
 
}

* OOM 발생 상황

 - GC root 참조에 도달하는 객체가 더 이상 어플리케이션 코드에서 사용하지 않음. 이것이 Java Memory Leaks

 - 너무 많거나 너무 큰 객체. 그래서 거기에 이용할 수 있는 충분한 힙이 없다. 

 - 너무 많은 임시 객체들. 

    So there is just for a short time not enough memory

   그래서 짧은 시간 동안 충분한 메모리가 없습니다.

 


Java Memory Leaks

* 객체가 GC root reference 를 가지고 있는데 더 이상 안쓴다면 메모리 누수가 발생한다.