Memory leaks can be extremely detrimental to your app strategy, because they not only lead to app crashes but affect the performance of the whole device and will deteriorate performance. A good deal of this chapter is devoted to background, because to prevent leaks, you need to understand how Android can have them in general, and specifically how threads and thread communication can cause them. The chapter does, however, offer strategies for managing the risk of memory leaks involved with threading, through correct design and lifecycle handling.
Memory leaks can occur on different occasions for each of the asynchronous techniques used on Android and described in Part III. So this chapter takes a general approach, and specific practical measures will be discussed when each of the asynchronous techniques is explained in detail.
The Dalvik VM is a memory-managed system that frequently reclaims allocated memory with the garbage collector (GC) from the shared memory, known as the heap, when it grows too large. Each process—and consequently each application—has its own VM and its own garbage collector. In spite of this, an application can fill up the heap with allocated objects that cannot be reclaimed in time, which causes memory leaks.
A memory leak is sometimes strictly defined as memory allocated by the application that is not used anymore, but never identified by the GC as memory that can be reclaimed. Hence, the memory is occupied ...