简体   繁体   English

是java原始垃圾收集

[英]are java primitives garbage collected

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? 如果我在Java中的方法中声明一个int(或任何原始类型),那么该函数返回时该内存是否已释放,或者它是否必须在垃圾收集器清除之前一直存在?

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. 我知道在C中,堆栈指针被重置并立即释放内存,我知道Java中的对象必须被垃圾收集,但我不知道基元会采用哪种方法。

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. 那是当java可能进来并且垃圾收集的时候。 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. 正如其他答案中所述,没有必要对它们进行GC。

This is very much analogous to malloc and free in C. 这非常类似于malloc并且在C中是free的。

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. 当你将一些内存malloc到C中的一个变量并且你的函数返回时,该指针的内存被释放但不是它指向的内存。

When you create an object in java (presumably with the new keyword) you are allocating memory for it. 当你在java中创建一个对象(可能是使用new关键字)时,你正在为它分配内存。 However, you never explicitly call free in java. 但是,你永远不会在java中显式调用free The JVM will detect when the freeing needs to be done. 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. 您可以将引用设置为null以告诉JVM您不再需要它,但通常最好只使用最小范围。

基元在堆栈上分配,因此在函数返回时释放它们的内存。

is that memory freed the moment the function returns, or does it have to hang around until the garbage collector cleans it? 是函数返回时释放的内存,还是它必须在垃圾收集器清理之前一直闲置?

The primitives declared inside the method are stored on the stack frame of that method. 在方法内声明的基元存储在该方法的堆栈帧中。 Since the stack frame is destroyed as soon as the method returns, the space allocated to local variables are freed. 由于一旦方法返回就会销毁堆栈帧,因此释放分配给局部变量的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM