If I have a class delete itself, should its internal methods stop executing? I have a class B that tells class A to remove B from A’s ArrayList. I’m fairly certain B only exists in A’s ArrayList, and so when I remove it, it should be deleted, right? (NOTE: I’ve included a Serializable implementation just in case that would have anything to do with how the VM handles my classes, but I did not write in the read- and writeObject methods here. I doubt it will have anything to do with this issue though.)
public class A implements Serializable, B_Listener {
ArrayList<B> bArray;
public A() {
bArray = new ArrayList<SomeObject>();
bArray.add(new B(bArray.size(), this));
}
@Override
public void deleteAtIndex(int index) {
bArray.remove(index);
}
}
public class B implements Serializable {
B_Listener listener;
int index;
public B(B_Listener listener, int index) {
this.listener = listener;
this.index = index;
}
//This is called at some point in a B's lifetime.
private void selfDestruct() {
listener.deleteAtIndex(index);
Log.w("B.class", "Should this not output? It does.");
}
}
public interface B_Listener {
public void deleteAtIndex(int index);
}
So the Log.w message executes when I don’t believe it should. Therefore, I’m afraid I’m creating java’s memory leaks. I’ve looked and looked throughout my code trying to find where B might be held by a pointer, but I’ve come up with nothing besides what I intended.
So then I’m asking if garbage is collected at a different time than when B is deleted on my end. If this is the case, then is it safe to say for the time being that I in fact am not holding objects I do not intend to hold?
Extra (NOTE: this might be hard to follow, everything above this should suffice for the problem):
I also have this tagged with Android-Views because I’m developing on Android: my B class holds View objects that point to B as a listener. When I removeView, the View manager or whatever Android has should no longer point to the View, I believe, and when I delete B, all its internal Views should also be deleted, meaning they can no longer hold B in existence by their own listener pointers. I’m just talking this out to see if my understanding here is correct.
Of course not.
A method will only “stop executing” if it
returns, if an exception is thrown, or if the thread is aborted.The whole point of garbage collection is that it is invisible to you. Barring special tricks (such as WeakReferences, or checking free memory), it is impossible to tell whether an object has been garbage collected – if you can check whether it exists, that means that you have a reference to it, so it cannot be collected.