Imagine this sample java class:
class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private A a; B() { a = new A(); a.addListener(new Listener() { void listen() {} } }
Do I need to add a finalize method to B to call a.removeListener? Assume that the A instance will be shared with some other objects as well and will outlive the B instance.
I am worried that I might be creating a garbage collector problem here. What is the best practice?
I just found a huge memory leak, so I am going to call the code that created the leak to be wrong and my fix that does not leak as right.
Here is the old code: (This is a common pattern I have seen all over)
Clearly, this is bad. Many Leaky’s are being created and never get garbage collected because the listeners keep them alive.
Here was my alternative that fixed my memory leak. This works because I only care about the event listener while the object exists. The listener should not keep the object alive.