0

As a disclaimer, I'm out of my depth here, my friend is the one who's actually facing this problem and I'm curious about what's going on.

I come from a more javascript/node.js background, so as I understand it

let a = 10
setTimeout(() => (a = 20))
a = 0;

a = 20 will always execute last, in other words, after a = 0

My friend has a piece of code which is similar, but was written for android

// handler is created somewhere in this same thread
a = 10;
handler.sendMessage(20);
a = 0;

He claims, the handler's handleMessage method has a reference to a, and will set a to 20 when the queue is ready.

The problem is after sometime, in a different thread, when he checks a's value, most of the time it's 20 but very rarely it's 0. He's also very sure that handleMessage has been executed already by that point. How does this happen?

Is handleMessage not guaranteed to be ran last like my example in javascript? If not how do I solve this gracefully?

Sorry for my awful pseudo codes but I'm really curious about this, would really appreciate it if somebody can point me in the right direction.

5
  • @Mark_M sorry if I wasn't being clear enough, my friend's code is in android, not node. sendMessage is a method of Handler class in android so the value 20 is being delivered to a message queue which I assumes is similar to javascript event loop. I guess what I'm asking here is essentially the difference between those two. Commented Oct 26, 2017 at 17:19
  • 1
    Tagging this node and javascript is not going get great answers when the question is about java and android. Commented Oct 26, 2017 at 17:23
  • @Mark_M Very true, I tagged this java but was removed by an editor, so I added android now. Sorry for the confusion. Commented Oct 26, 2017 at 17:32
  • You're onto the core of the issue here, setting an async execution and then attempting to execute a blocking call does not guarantee that the async invocation will execute last: stackoverflow.com/questions/26224226/… Commented Oct 26, 2017 at 17:59
  • @CristianCavalli I see no mention of that in the link you provided, only that the execution order of items in the queue is undefined. Not the execution order between the stack and the queue. Am I reading it wrong? Commented Oct 26, 2017 at 21:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.