yeg*_*256 0 java garbage-collection
这是数据提供者:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试这样做(只是一个例子,了解它是如何工作的):
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?
Run Code Online (Sandbox Code Playgroud)
我想知道GC是否会破坏所有Item对象,或者它们将保留在内存中,因为我List保存10000个链接到它们的部分(text)?
因为您没有保留对Item对象的引用,只是对字符串,所以Item对象符合GC的条件.字符串不是,因为它们被引用.
循环的第一次迭代后,你有这个:
+------+
| item |
+------+
| text |----+
+------+ | +---------+
+-> | "Hello" |
| +---------+
+-------+ |
| texts | |
+-------+ |
| 0 |---+
+-------+
因此,无论item和texts指向字符串,但没有指回item,这样Item可以GC'd.
略有偏离主题:
您显示的示例将只有一个String在列表中引用10,000次的实例,因为它是一个字符串文字,并且字符串文字是intern自动的.但如果在每种情况下它都是不同的字符串,答案就不会改变.字符串与Items 分开.