Garbage Collection

One of the great benefits of Java is garbage collection. The garbage collector frees (or reclaims) memory as objects are no longer in use. For example, the Record object allocated in doSomethingWithAllRecords() in Listing 4–15 is made eligible for garbage collection when the method returns, as a reference to that object no longer exists. There are two very important things to note:

  • Memory leaks can still exist.
  • Use the garbage collector to help you manage memory as it does more than just freeing memory not in used anymore.

Memory Leaks

As memory can be reclaimed only when an object is no longer referenced, a memory leak can occur when a reference to an object is kept around. A typical example from the Android documentation ...

Get Pro Android Apps Performance Optimization 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.