Is there a way to free memory in Java, similar to C's free() function? Or is setting the object to null and relying on GC the only option?
解决方案
Java uses managed memory, so the only way you can allocate memory is by using the new operator, and the only way you can deallocate memory is by relying on the garbage collector.
This memory management whitepaper (PDF) may help explain what's going on.
You can also call System.gc() to suggest that the garbage collector run immediately. However, the Java Runtime makes the final decision, not your code.
Calling the gc method suggests that
the Java Virtual Machine expend effort
toward recycling unused objects in
order to make the memory they
currently occupy available for quick
reuse. When control returns from the
method call, the Java Virtual Machine
has made a best effort to reclaim
space from all discarded objects.
本文解释了Java中如何避免手动内存释放,通过new操作分配内存,垃圾回收机制确保内存管理。System.gc()仅建议而非强制GC,对象置null依赖于自动回收。
10万+

被折叠的 条评论
为什么被折叠?



