How to manually free primitive variables?

╄→尐↘猪︶ㄣ 提交于 2019-12-13 23:16:25

问题


I understand that in Java, we usually do not need to worry about deleting variables manually since garbage collection can take care of that. However, in some situations, we need to free an object before garbage collection takes effect in order to prevent memory leak. To free an object, we can simple set its reference to be null.

Now my question is, how can we manually free a primitive variable? If there is no way to manually free a primitive variable, then why, since there is a mechanism to manually free a reference variable?


回答1:


This question is a nonsense. It is not true that by setting null you delete anything. And primitive types cannot be "deleted". The memory space for local variables is allocated as long as they are in scope.




回答2:


You cannot set a primitive type (int, float, double, char... a few others; you get the picture) to null. If you try, you'll get a NullPointerException.

There is no concept of delete in Java. Java handles all memory management automatically via internal reference counters. This process is commonly referred to as the Garbage Collector.

Once an Object goes out of scope, it is made available for Garbage Collection and its memory may be reclaimed at any time. You do not need to worry about de-allocating the memory manually in Java. While primitives are not freed directly by the Garbage Collector (see 'are java primitives garbage collected'), you still don't need to worry about deleting them.

(The topic of Garbage Collection is obviously much deeper and more complicated than that, but I think this post is a fair 100,000-foot summary.)



来源:https://stackoverflow.com/questions/39419901/how-to-manually-free-primitive-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!