質問

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