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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top