I'm in a situation where I have a static list caching some references. As this is a static list, I want to use WeakReference so I don't keep my objects in memory uselessly.
The issue - I think - I have is that one of the references is an anonymous class. My fear is that if I store the anonymous class as a WeakReference, it might be collected really quickly, and if I store the anonymous class as a strong reference, it will hold a reference to the class that constructed the anonymous class.
I don't know if my explanation is clear, so here is a piece of code:
public interface Callback {
void call();
}
public class A {
public void doIt() {
B.register(this, new Callback() {
public void call() {
// do something
}
});
}
}
public class B {
private static final List<Item> ITEMS = new LinkedList<>();
public static void register(Object key, Callback callback) {
Item item = new Item();
item.key = new WeakReference<>(key);
// ??
item.callback = new WeakReference<>(callback);
ITEMS.add(item);
}
private static class Item {
private WeakReference<Object> key;
private WeakReference<Callback> callback;
}
}
Basically, if in Item 'callback' is a weak reference, it might be garbage collected before I even get the chance to use it. And if in Item 'callback' is a standard reference, the instances of 'A' will never be garbage collected.
So my first question: is my understanding right? Second question: is there a way to make it work or do I have to change the design?
Thanks.