1

Is setting a null value to an object good enough for garbage collection to collect and clear up memory in Java (Android)?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
StealthOne
  • 194
  • 9
  • 1
    make sure there are no reference to the original object, then garbage collection can be made, but I don't think its guaranteed. – dchhetri Apr 16 '13 at 23:46
  • Setting a `null` value to an object is completely unrelated to its GC. It's much more common for objects to get GC'd just because nobody references them anymore. – Louis Wasserman Apr 17 '13 at 00:54

3 Answers3

4

If all references to an object are set to null then it will eventually be cleaned up by the garbage collector. Whether that's enough depends on what other resources the object holds (like file handles or db handles that can be leaked) and whether the garbage collector runs frequently enough to free it before you need the memory. Large objects like bitmaps frequently have a function that can be called to free the memory early to avoid that problem (bitmap's recycle() is an example).

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
2

Yes. That's how objects are freed in Java. Once they are freed, they become eligible for garbage collection, and are collected at some later time.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
0

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.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256