I have doubt about interfaces and memory leaks, considering the block of code below, could it bring to a memory leak? If so what's the best solution or alternative?
public class MyClass {
public interface MyClassListener{
doStuff();
}
public doSomething(){}
}
public class OtherClass {
private List<MyClass> list = new ArrayList<MyClass>();
private boolean doingStuff = false;
public void setListener(MyClassListener list) { //Sets the listener}
public MyClass.MyClassListener listener = new MyClass.MyClassListener() {
public void doStuff(){ doingStuff = true; }
}
public void addMyClass(MyClass obj) {
obj.setListener(listener);
list.add(obj);
}
public void doSomethingInMyClass(int index) {
....update some stuff....
list.get(index).doSomething();
}
}
i know i could declare the variable listener
as static
so it wont hold a reference to OtherClass
and assign that reference to a WeakReference
but am i going to a memory leak anyway?
Since the reference will hold a reference to an object containing a list which contains my object. It is like a chain.
Update
I updated my question, as you can see MyClass
has a method called doSomething()
, instead OtherClass
has a method called doSomethingInMyClass
which calls the doSomething
method but updates some parameters.
What i want is to avoid to use doSomethingInMyClass
and get notified of the changes anyway.