are java primitives garbage collected

2019-01-15 08:38发布

问题:

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.

回答1:

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.



回答2:

Primitives are allocated on the stack, so their memory is freed the moment the function returns.



回答3:

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.