具有递归函数的Java垃圾回收 [英] Garbage Collection in Java with Recursive Function

查看:142
本文介绍了具有递归函数的Java垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道对象变得无法访问,并在正常循环的每次迭代中标记为垃圾收集。递归调用呢?例如:
$ b

  public void doWork(){

Object a = new Object();

....一些工作与...

this.sleep(60000);
doWork();





是对象(即'a' )在第一次递归中被标记为垃圾回收,一旦第二次递归开始或者它需要被显式标记为空,因为外部函数永远不会因为递归而结束。 在每次递归调用期间,局部变量(这里是参考a)被压入栈中。 局部变量是GC根。在第二次递归调用期间,新引用被压入堆栈。但是,第一个引用仍然存在,因此该对象仍然可以访问,因此无法进行垃圾回收。



因此,如果您希望第一个创建的对象被标记对于垃圾收集(当函数尚未完成时),您应该明确地将a设置为null。



以下是理解GC的有用链接: http://javabook.compuware.com/content/memory/how-garbage- collection-works.aspx


I know that objects become unreachable and marked for garbage collection in every iteration of a regular loop. What about recursive calls? Something like:

public void doWork() {

    Object a = new Object();

    ....some work with a...

    this.sleep(60000);
    doWork();


  }

Is the object (i.e. 'a') in the first recursion marked for garbage collection once the second recursion begins or does it need to be explicitly marked null since the outer function never finishes because of the recursion.

解决方案

During each recursive call the local variables(here the reference "a") are pushed onto the stack. Local variable are GC roots. During the second recursive call the new reference is pushed onto the stack. However, the first reference is still there and thus the object is still reachable and thus can't be garbage collected.

Thus if you want the first created object to be marked for garbage collection(while the function hasn't yet finished) you should explicitly set "a" to null.

Here is a useful link to understand GC: http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx

这篇关于具有递归函数的Java垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆