什么时候有资格进行垃圾回收的对象? [英] When is an object eligible for garbage collection?

查看:84
本文介绍了什么时候有资格进行垃圾回收的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在约瑟夫·阿尔巴哈里(Joseph Albahari)的《 C#5.0》一书中,我发现了这一点

In the book C# 5.0 in a nutshell by Joseph Albahari I found this

它说一旦您通过最后使用变量的代码行,它所引用的对象就可以进行垃圾回收(也就是说,如果没有其他变量持有对该对象的引用).

where it says as soon as you pass the line of code where a variable is last used, the object referenced by it is eligible for garbage collection (That is if no other variable holds a reference to that object).

但是,根据UC Berkley的演讲,只要引用了对象存在于堆栈中,不会被垃圾回收.我的理解是,直到方法返回,变量才会停留在堆栈上.这意味着它所引用的任何对象都将处于活动状态,直到方法返回为止.

However according to this lecture from UC Berkley, as long as a reference to the object exists on the stack, it won't be garbage collected. My understanding is, until the method returns, the variable stays on the stack. Which means any object referenced by it is alive until the method returns.

这是书中的错误吗,还是java和.net垃圾回收工作不同?

Is this an error in the book or does java and .net garbage collection work differently?

推荐答案

但是,根据加州大学伯克利分校的本次演讲,只要在堆栈上存在对对象的引用,就不会对其进行垃圾回收.

However according to this lecture from UC Berkley, as long as a reference to the object exists on the stack, it won't be garbage collected.

您是对的.您所缺少的是引用不再存在于堆栈中.

You're right. What you're missing is that a reference no longer exists on the stack.

对于在堆栈上构造对象的代码:

For the code that constructs an object on the stack:

StringBuilder ref1 = new StringBuilder("object1");

变量ref1存储在堆栈中的 some 内存位置:

the variable ref1 is stored on the stack, in some memory location:

                 0x403730:
Stack Pointer -> 0x40372C: pointer to ref1
                 0x403728: saved value of EBP
                 0x403724: saved value of return address
                 0x403720

现在是下一行:

StringBuilder ref2 = new StringBuilder("object2");

指向ref2的指针将存储在哪里?在堆栈上:是的.但是哪里在堆栈上?当然,在相同的内存位置!

Where is the pointer to ref2 going to be stored? On the stack: yes. But where on the stack? In the same memory location that was being used for ref1 of course!:

                 0x403730:
Stack Pointer -> 0x40372C: pointer to ref2
                 0x403728: saved value of EBP
                 0x403724: saved value of return address
                 0x403720

简单地将另一个值推入堆栈将是愚蠢的:

It would be silly to simply push another value onto the stack:

Stack Pointer -> 0x403730: pointer to ref2
                 0x40372C: pointer to ref1
                 0x403728: saved value of EBP
                 0x403724: saved value of return address
                 0x403720

这很愚蠢,因为不再需要ref1.

It would be silly because ref1 isn't needed anymore.

这就是ref1有资格进行垃圾回收的原因:不再有对其的引用.

That's why ref1 is eligible for garbage collection: there are no longer any references to it.

这篇关于什么时候有资格进行垃圾回收的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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