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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.