1

我有以下一段代码:

 List<String> list = new ArrayList<String>();
  //  WeakReference<List> wr = new WeakReference<List>(list);
    System.out.println(" before tot memory... " +  Runtime.getRuntime().totalMemory());
    System.out.println(" before free memory... " +  Runtime.getRuntime().freeMemory());
    for(int i =0; i<100; i++)
    list.add(new String("hello"));
    //System.gc();
    list = null; //forcefully end its life expectancy
    System.out.println(" after tot memory... " +  Runtime.getRuntime().totalMemory());
    System.out.println(" after free memory... " +  Runtime.getRuntime().freeMemory());
    System.out.println(" after memory used ... " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
   // System.out.println(" weak reference " + wr.get());

当我运行上面的代码时,我可以看到可用内存是 361064(在我的系统中,但是这个值可能会有所不同)

但是当我使用 System.gc() 和注释 list=null 运行上面的代码时,我可以看到我的可用内存即将到来(在这种情况下为 160944)小于上面的测试用例。在这两种情况下,对象都会从内存中删除。但是为什么这些值不同。

4

2 回答 2

1

列表=空;取消任何引用将自动导致垃圾收集。当您注释此行时,引用列表仍然处于活动状态,那么即使您调用System.gc()它也不会被垃圾收集。

当您显式调用gc()时,已经无效或超出范围的引用只会被垃圾收集。

于 2012-04-06T07:01:27.493 回答
0

GC 通过查看内存中的所有对象以objects which are no longer being referenced在程序中找到任何对象来工作。可以删除这些未使用的对象,以便为新的内存对象腾出空间。

因此,如果任何对象仍在被引用,即使您调用也无法进行垃圾收集System.gc()。如果您可以在代码中引用一个对象,如何对它进行垃圾回收?

通过调用list = nulllist变量引用的对象不能被再次引用,因此它有资格获得垃圾收集。

于 2012-04-06T07:20:23.930 回答