* Process 는 자기 자신만의 VM 과 GC 를 가진다


> Thread 는 GC 의 root 이다





코드 

 구조

 설명

A class {

B Thread() {

void run() {

new SampleObject();

}

}

}

 


지역 Class 및 Anonymous Inner Class 로 정의된 Thread 는 실행되는동안 GC Root 에서 Outer Class 의 객체 인스턴스로  도달 가능하게 유지한다

→ 즉, Thread 가 수행되는 동안, Outer Class Object 도 Heap 에 남아있다

A class {

static B Thread() {

void run() {

new SampleObject();

}

}

}

 



 Static Inner Class 는 객체가 아닌 클래스의 인스턴스이므로, 객체가 아닌 클래스에 대해 참조를 유지한다

→ Thread 가 수행 중이더라도 Outer Class Object Heap 에서 제거 될 수 있다 (클래스의 인스턴스는 Heap 이 아닌 Method Area 에 존재하기 때문)

A class {

void method {

B Thread = new B (new Runnable() {

void run() {

new SampleObject();

}

});

}


static class B Thread() {

B (Runnable r) {

}

}

}



 Runnable 이 static class 내부가 아닌 객체 인스턴스에 존재하기 때문에 왼쪽과 같은 구조를 가지게 된다

→ Thread 가 참조하는 Runnable Object 가 Outer Class Object 를 참조하고 있으므로 Heap 에 남아있다



* Static Inner Class 를 통한 Memory Leak 최소화


> Context 나 Thread 의 Outer Class 참조 등에 따른 Memory Leak 을 방지하기 위해서는, inner class 보다는 static inner class 를

사용하는 것이 안전하다


> 단점은 Outer Class 의 Member Variable 을 참조할 수 없다

 : 단점 해결을 위해 Weak Reference 를 사용할 수 있다 (Weak Reference 를 사용하게 되면 GC 의 Reference Counting 에서 제외됨)


A Class {

private int mField;


private static B Thread {

private final WeakReference<A> mAObject;


B (A object) {

mAObject = new WeakReference<A>(object);

}


void method() {

if (mAObject.get() != null) {

mAObject.get().mField = 5;

}

}

}

}


'SW > ::: Java' 카테고리의 다른 글

String  (0) 2020.10.05
Late Binding  (0) 2020.10.04
////200927 JDK 15 // early16  (0) 2020.09.27
@FunctionalInterface  (0) 2020.09.15
Java Synchronization (Locking Mechanism)  (0) 2019.09.07

+ Recent posts