Avoiding memory leaks
The best way of avoiding a memory leak is to write code that does not contain any leaks in the first place. In other words, objects that we no longer need should not have connections back to the stack, as that prevents the garbage collector from reclaiming them. Before we get into techniques that help you avoid leaks in your code, let us first fix the leak presented in Figure 7.1. Figure 7.6 presents the leak-free code:
Figure 7.6 – Leak-free program
In Figure 7.6, the infinite loop remains. However, lines 19 to 23 are new. In this new section, we increment an i local variable every time we add a Person reference to the ArrayList object. Once we have done this 1,000 times, we re-initialize our list reference. This is crucial as it enables the garbage collector to reclaim the old ArrayList object and the 1,000 Person objects referred to from the ArrayList object. In addition, we reset i back to 0. This will solve the leak. ...