title: Is WeakReference a good type in order to reference my custom view inside a static inner class?
body: <p>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 :</p>
  
  <pre><code>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&lt;ChessView&gt;(view);
          }
  
          @Override
          public void handleMessage(Message msg) {
              relatedChessView.get().invalidate();
          }
  
          private WeakReference&lt;ChessView&gt; relatedChessView; 
      };
  
      private InvalidateHandler invalidateHandler;
  
  }
  </code></pre>
  
  <p>As you can see :</p>
  
  <ol>
  <li>I am creating a static inner class, subclass of the Handler class : as the android developpers guide recommands to avoid direct inner classes inside View subclasses</li>
  <li>The Handler static inner class makes a call to the invalidate() method of my custom ChessView : so I decided to "wrap it" inside a WeakReference, as the android developper guide recommands to avoid hard references on View instances.</li>
  </ol>
  
  <p>So here my questions :</p>
  
  <ol>
  <li>Do I avoid memory leaks this way ? </li>
  <li>Is WeakReference the best type, or should I use a SoftReference instead ?</li>
  <li>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() ?</li>
  </ol>
  
  <p>Thanks in advance, and apologizes if my question is bad formulated.</p>