Chapter 6. Memory Management

Memory leaks can be extremely detrimental to your app strategy because they not only lead to app crashes but also 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 II. So this chapter takes a general approach, and specific practical measures will be discussed when each of the asynchronous techniques is explained in detail.

Garbage Collection

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.

Note

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 ...

Get Efficient Android Threading now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.