Search code examples
javaandroidmultithreadingjava-memory-model

Is this way of passing objects between threads safe under JMM?


I'm looking for a safe way to pass an object from a background thread to the UI thread. Does the code below do it safely?

// on background thread
final HugeObject object = constructHugeObjectFromDatabaseAndNetwork();
uiThreadHandler.post(new Runnable() { 
    public void run() { doSomethingWithObject(object); }
});

I.e., do JMM rules allow the object to be in fact partially constructed during the doSomethingWithObject call? Also, how relevant JMM is for Android and its virtual machine?


Solution

  • Yes - handlers are there to do exactly that: exchange information across threads in a thread safe way.

    In practice, handlers use a thread safe (synchronized) message queue to post messages, creating a happens-before relationship between your code and whatever will happen on the UI with your object.

    Recent versions of android comply with the JMM.