title: "Impossible" NPE in a multi-threaded situation
body: <p>I have some inherently asynchronous code in an Android app. I'm using RxJava2. The class <code>Thing</code> is not under my control (but <code>ThingFactory</code> is). In one method (<code>createThing()</code>), a new <code>Thing</code> is instantiated. <code>Thing</code>'s constructor does some work and, when it is complete, notifies us via a callback <code>onThingInitialized()</code>. At the point that callback is called, we should be guaranteed that <code>thing</code> exists. In the callback, I schedule work to happen on a separate thread (in this case, using RxJava2, but I don't think it should matter). There is nowhere in this code that I call anything like <code>thing = null</code>. So, once it's set, it's set forever.</p>
  
  <p>I threw a <code>volatile</code> onto it because the instance <em>does</em> get updated, but never nulled. If I'm mis-using it, please feel free to berate me.</p>
  
  <pre><code>public class UsesAThing implements ThingCallbacks {
  
      private volatile Thing thing; // I feel like I don't understand 'volatile'
  
      // I call this method
      public void createThing() {
          thing = thingFactory.newThing(param1, param2);
      }
  
      // Thing's constructor does some work and notifies us when it's done
      @Override
      public void onThingInitialized() {
          // Called on main thread, but I want to do some IO work, so:
          Schedulers.io().scheduleDirect(() -&gt; {
              thing.doStuff(); // NPE!
          });
      }
  }
  </code></pre>
  
  <p><strong>How is an NPE possible there?</strong></p>
  
  <p><strong>EDIT:</strong></p>
  
  <p><code>Thing</code>'s constructor does its work asynchronously. As I said, this is in an Android environment, so the work it's actually doing is binding to a <code>Service</code>. When the <code>Service</code> is bound, its <code>ServiceConnection::onServiceConnected()</code> callback is hit, which itself actually fires up an <code>AsyncTask</code> which, in its <code>onPostExecute()</code> callback, calls the <code>onThingInitialized()</code> callback.</p>
  
  <p><strong>EDIT 2:</strong></p>
  
  <p>I should also note that this NPE doesn't happen all the time. I've run through this code hundreds of time, and I've only seen it occur once.</p>
  
  <p><strong>EDIT 3: Sample calling code</strong></p>
  
  <p>I didn't provide sample code because it's about as simple as one might imagine, but here's what it looks like:</p>
  
  <pre><code>Flowable.just(1)
      .subscribeOn(Schedulers.io())
      .subscribe(i -&gt; createThing());
  </code></pre>