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