问题描述
如果我在 Java 中的方法中声明一个 int(或任何原始类型),该内存是在函数返回的那一刻被释放,还是必须在垃圾收集器清理它之前一直存在?
If I declare an int (or any primitive type) within a method in Java, is that memory freed the moment the function returns, or does it have to hang around until the garbage collector cleans it?
我知道在 C 中堆栈指针被重置并立即释放内存,并且我知道 Java 中的对象必须被垃圾收集,但我不知道原语会采用哪种方法.
I know that in C the stack pointer is reset and that immediately frees memory, and I know that objects in Java have to be garbage collected but I don't know which approach would be taken with primitives.
推荐答案
当一个方法被返回时,它的栈上的变量总是立即被释放(当然,释放是指栈帧被销毁,也是像局部变量一样附加到它的所有内存).
When a method is returned, the variables on its stack are always immediately freed(Of course, by freed I mean that the stack frame gets destroyed, and so does all memory attached to it like local variables).
但是,如果该变量是一个对象,那么它的值就是一个指针.包含对象的实际内存(也可能具有指向其他对象的指针)将在堆上.当堆栈上的引用被释放时,该对象只是闲置而没有任何人引用它(除非您将引用放在其他地方).那是java可能进来并收集垃圾的时候.那就是对象被标记为收集,下次收集器运行时它将清理该对象.
However, if that variable is an object, then its value is a pointer. The actual memory containing the object(which may have pointers to other objects as well) would be on the heap. When the reference on the stack gets freed, the object is just sitting around without anybody referencing it(unless you put a reference somewhere else). That is when java may come in and garbage collect. That is the object gets flagged for collection, and the next time the collector runs it will clean up this object.
基元有一个原始值,而不是指针.因此,正如其他答案中所述,无需对它们进行 GC.
Primitives have a raw value, and are not pointers. So as stated in other answers, there is no need to GC them.
这非常类似于 C 中的 malloc
和 free
.
This is very much analogous to malloc
and free
in C.
当你 malloc 一些内存到 C 中的一个变量并且你的函数返回时,该指针的内存被释放,但不是它指向的内存.
When you malloc some memory in to a variable in C and your function returns, the memory for that pointer is freed but not the memory it was pointing to.
当您在 java 中创建一个对象时(可能使用 new
关键字),您正在为它分配内存.但是,您永远不会在 java 中显式调用 free
.JVM 会检测何时需要释放.
When you create an object in java (presumably with the new
keyword) you are allocating memory for it. However, you never explicitly call free
in java. The JVM will detect when the freeing needs to be done.
您可以将引用设置为 null 以告诉 JVM 您不再需要它,但通常最好只使用最小范围.
You can set references to null to tell the JVM that you don't need it anymore, but it's often better to just use minimal scope.
这篇关于是java原语垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!