代码之家  ›  专栏  ›  技术社区  ›  yegor256

我的物品会被垃圾收集吗?

  •  0
  • yegor256  · 技术社区  · 12 年前

    这是数据提供程序:

    class Item {
      private String text;
      public Item(String txt) {
        this.text = txt;
      }
      public String get() {
        return this.text;
      }
      public static Item next() {
        return new Item("hello");
      }
    }
    

    现在我正在尝试这样做(只是一个例子,以了解它是如何工作的):

    List<String> texts = new LinkedList<>();
    for (int i = 0; i < 10000; ++i) {
      Item item = Item.next();
      texts.add(item.get());
    }
    // do we still have ten thousand Items in memory,
    // or they should already be garbage collected?
    

    我想知道GC是否会毁掉所有 Item 对象,否则它们将留在记忆中,因为我 List 将10000个链接保存到其部件( text )?

    1 回复  |  直到 12 年前
        1
  •  8
  •   T.J. Crowder    12 年前

    因为你没有保留对 Item 对象,仅限于字符串 项目 对象符合GC条件。字符串不是,因为它们被引用了。

    在循环的第一次迭代之后,您将得到以下内容:

    +------+
    | item |
    +------+
    | text |----+
    +------+    |   +---------+
                +-> | "Hello" |
                |   +---------+
    +-------+   |
    | texts |   |
    +-------+   |
    | 0     |---+
    +-------+

    所以两者 item texts 指向字符串,但没有指向后面 项目 因此 项目 可以是GC’d。


    轻微地 离题:

    如图所示,您的示例只有一个 String 在列表中被引用10000次的实例,因为它是字符串文字,而字符串文字是 intern 'd自动。但是,如果在每种情况下都是不同的字符串,答案就不会改变。字符串与 项目 s