是垃圾收集的java原始资料 [英] are java primitives garbage collected

查看:125
本文介绍了是垃圾收集的java原始资料的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Java中的方法中声明了一个int(或任何基本类型),那么当函数返回时是否释放了内存,还是必须在Java垃圾收集器清理它之前一直存在?



我知道在C语言中,堆栈指针被重置,并立即释放内存,我知道Java中的对象必须被垃圾回收,但我不知道基元会采用哪种方法。

解决方案

当返回一个方法时,堆栈中的变量总是被立即释放(当然,通过释放,我的意思是堆栈框架被破坏,所有附加到它的内存也像本地变量一样)。

但是,如果该变量是一个对象,那么它的值就是一个指针。包含对象的实际内存(可能也有指向其他对象的指针)将位于堆上。当堆栈中的引用被释放时,该对象只是坐在一个没有任何人引用它的地方(除非你把引用放在别的地方)。那是什么时候java可以进来并垃圾收集。这是该对象被标记为收集对象,下一次收集器运行它将清理该对象。

原始图有一个原始值,而不是指针。正如其他答案中所述,不需要GC。



这与 malloc 非常类似,和 free in C.



当你将一些内存malloc添加到C中的一个变量中并且你的函数返回时,该指针的内存被释放,但不是它指向的内存。

当你在java中创建一个对象(大概是用 new 关键字)时,你正在为它分配内存。但是,您绝对不要在java中明确地调用 free 。 JVM将检测何时需要完成释放操作。



您可以将引用设置为null,以告诉JVM您不再需要它,但通常会更好只使用最小范围。

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?

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).

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.

Primitives have a raw value, and are not pointers. So as stated in other answers, there is no need to GC them.

This is very much analogous to malloc and free in 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.

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.

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原始资料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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