为对象设置一个null
值是否足以让垃圾收集在 Java (Android) 中收集和清理内存?
3 回答
如果对一个对象的所有引用都设置为 null,那么它最终会被垃圾收集器清理掉。这是否足够取决于对象拥有的其他资源(例如可能泄漏的文件句柄或数据库句柄)以及垃圾收集器是否足够频繁地运行以在您需要内存之前释放它。像位图这样的大对象经常有一个函数可以被调用来提前释放内存以避免这个问题(位图的 recycle() 就是一个例子)。
是的。这就是在 Java 中释放对象的方式。一旦它们被释放,它们就有资格进行垃圾收集,并在稍后的某个时间被收集。
The garbage colletor does mark and sweep.
When using mark-and-sweep, unreferenced objects are not reclaimed immediately. Instead, garbage is allowed to accumulate until all available memory has been exhausted. When that happens, the execution of the program is suspended temporarily while the mark-and-sweep algorithm collects all the garbage. Once all unreferenced objects have been reclaimed, the normal execution of the program can resume.
http://www.brpreiss.com/books/opus5/html/page424.html. The link has details regarding how mark and sweep works.
http://chaoticjava.com/posts/how-does-garbage-collection-work/
Technical details of Android Garbage Collector
If you set your variable to null. the variable will be available for garbage collection. However it depends on the virtual machine (dalvik) to decide when to garbage collect. It also depends on the heap size. More the heap size more frequent garbage collection. http://www.youtube.com/watch?v=_CruQY55HOk. The guy in the video gives a big warning about using large heap since it leads to more frequent garbage collection there causing your application to pause.
If the current running operation requires more memory and the memory is not available, the garbage collector kicks in to free memory.( even after which required memory space is not avaialable you will get memory leaks).
http://developer.android.com/training/articles/perf-tips.html.
A quote from the above link. As you allocate more objects in your app, you will force a periodic garbage collection, creating little "hiccups" in the user experience.