I am writing a custom view by directly inheriting from the View class, and I am wondering whether I am making a good use of the WeakReference class. First, this is the most relevant part of my class :
public class ChessView extends View {
public ChessView(Context context, AttributeSet attrs, int defStyle) {
/* some code removed */
invalidateHandler = new InvalidateHandler(this);
new Thread(new Runnable() {
@Override
public void run() {
invalidateHandler.sendMessage(invalidateHandler.obtainMessage());
}
}).start();
}
/* some code removed */
private static class InvalidateHandler extends Handler {
public InvalidateHandler(ChessView view){
relatedChessView = new WeakReference<ChessView>(view);
}
@Override
public void handleMessage(Message msg) {
relatedChessView.get().invalidate();
}
private WeakReference<ChessView> relatedChessView;
};
private InvalidateHandler invalidateHandler;
}
As you can see :
So here my questions :
Thanks in advance, and apologizes if my question is bad formulated.
Do I avoid memory leaks this way ?
Yes, but this isn't necessary.
Is WeakReference the best type, or should I use a SoftReference instead ?
WeakReference
is the way to go in your case. SoftReference
and WeakReference
will be both available as long as there is a hard reference pointing to them. If there is no strong reference though, WeakReference
will more likely to be collected while SoftReference
will retain your object as long as there is no need to clean up memory (eg. SoftReference
will stick around longer).
And finally, will the custom view remains on the heap as long as the view is visible (or the related activity active) or may it be collected by the GC before, letting me with a null reference when calling relatedChessView.get()?
Yes, it will. As i mentioned above WeakReference
won't be collected while there are any Objects
holding the contained Object
's reference.
UPDATE: Fixed the information regarding Weak and Soft references based on @DeeV's answer to be more accurate.