Question

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?

Was it helpful?

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.

OTHER TIPS

It depends on the implementation of post(). There's no memory barrier in the quoted code, so it generally wouldn't be thread safe. But, in practice, it becomes very difficult to have one thread waiting for a task to run without using a barrier to exchange objects. That is likely to be the case here, and if so, it will be safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top