Java垃圾收集和null

时间:2012-04-06 06:58:40

标签: java garbage-collection

我有以下代码:

 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)比上面的测试用例少。在这两种情况下,都会从内存中删除对象。但是为什么这些值不同。

2 个答案:

答案 0 :(得分:1)

list = null; 取消任何引用都会自动导致垃圾回收。当您对此行发表评论时,参考列表仍然有效,那么即使您调用 System.gc(),也不会进行垃圾回收。

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

答案 1 :(得分:0)

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

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

通过调用list = nulllist变量引用的对象无法再次引用,因此有资格获取垃圾。

相关问题