1

与えられた:

 public class Trees {
    Trees t;

    public static void main(String[] args) {
        Trees t = new Trees();
        Trees t2 = t.go(t);
        t2 = null;
        // more code here : LINE 11
    }

    Trees go(Trees t) {
        Trees t1 = new Trees();
        Trees t2 = new Trees();
        t1.t = t2;
        t2.t = t1;
        t.t = t2;
        return t1;
    }
}

11 行目に到達したとき、ガベージ コレクションの対象となるオブジェクトはいくつありますか?

4

3 に答える 3

3

gc に適したオブジェクトの数を決定する方法について質問されました。これらの質問を解決する最も簡単な方法は、参照 (例では t、t1、t2) と実際のオブジェクト自体を示す図を描くことです。オブジェクトが参照に接続されていない場合、Java コードがそのオブジェクトにアクセスする方法がないため、オブジェクトはコレクションの対象になります。

このリンクは、例と図の描き方を示しています

http://radio.javaranch.com/corey/2004/03/25/1080237422000.html

于 2012-10-26T09:06:00.830 に答える
2

次の 3 つのオブジェクトを作成します。

Object "a": Trees t = new Trees();
Object "b": Trees t1 = new Trees();
Object "c": Trees t2 = new Trees();

11 行目では、変数 t (main で宣言されている) がまだオブジェクト "a" への参照を持っており、"a" から "b" と "c" の両方に到達できるため、ガベージ コレクションの対象となるものはありません。

于 2012-10-26T08:58:37.447 に答える
1

Based on your code snippet, when the control reaches your "line 11", no objects can be GCed.

Reason:

  • Trees t; is a field, and thus cannot be GCed now.
  • after calling go, t2 will equal null. However, in method go, each t1 and t2 point to the other, plus that the field t is pointing to one of them. So that no object can be GCed, because of reference chain:

t -> t2

t2 -> t1

于 2012-10-26T08:59:59.290 に答える