2009년 11월 2일 월요일

eligible for GC

10. public Object m() {
11. Object o = new Float(3.14F);
12. Object [] oa = new Object[1];
13. oa[0] = o;
14. o = null;
15. return oa[0];
16. }
When is the Float object, created in line 11, eligible for garbage collection?
A. Just after line 13.
B. Just after line 14.
C. Never in this method.

D. Just after line 15 (that is, as the method returns)

eligible 은 자격을 얻는 다는 뜻이다. 가비지 컬렉팅이 된다는 뜻은 쓰레기 수집 대상이 된다는 뜻인데, '자격'은 좀 우스운 표현이긴 하다.

float을 인스턴스 변수 o 가 가리키고 (난 포인터가 더 편해서 그냥 포인터 라고 하겠다)
oa[0] 배열에 o의 포인터를 넣고, oa를 리턴한다.

즉, 메소드가 끝날 때 까지는 포인터가 유지되므로 대상이 되지 않는다. 뭐, 쓰레기의 자격을 얻는다고 해도 바로 수집되지도 않는다. GC는 메모리 단편화 해결도 못하고 있다. 단편화 세미나 일주일 짜리 들었는데, 메모리만 연구하시는 박사 말씀을 들었을 때는 메모리 단편화는 평생 제대로 해결 못할 듯하다. 결국... Restart 혹은 Reboot이 주기적으로 필요하다는 말이다.


1. class Test {

2. private Demo d;

3. void start() {

4. d = new Demo();

5. this.takeDemo(d);

6. }

7.

8. void takeDemo(Demo demo) {

9. demo = null;

10. demo = new Demo();

11. }

12. }

When is the Demo object, created on line 3, eligible for garbage collection?

A. After line 5.

B. After line 9.

C. After the start() method completes.

D. When the takeDemo() method completes.

E. When the instance running this code is made eligible for garbage collection.



자바에서는 Call by reference 가 없다고 한다. 콜백은 함수포인터라고 생각 하지만 언어가 추구하려고 하는 방향이 copy 니까 그렇게 알아 두자.

정확히는 4 라인에서 d 포인터에 데모가 대입된다. 정확하게는 힙 영역에 생성된 데모 객체의 주소겠지.  take demo 메소드에서 demo 파라미터에 널을 넣고 새로운 데모를 대입한다. 그런데 복사된 파라미터라서 null 대입해도 private Demo d 인스턴스(포인터)는 여전히 Demo를 하나 가리키고 있다. 멤버변수라서 Test 객체가 어디서 생성되었다면 Test 객체 자체가 죽지 않는한 GC가 되지 않는다.

댓글 없음:

댓글 쓰기

국정원의 댓글 공작을 지탄합니다.

UPBIT is a South Korean company, and people died of suicide cause of coin investment.

 UPBIT is a South Korean company, and people died of suicide cause of coin. The company helps the people who control the market price manipu...