Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handler.post(runnable) doesnt always execute the run method in android

I have created a Handler instance in the main ui thread(mUIHandler) and from a worker thread(other thread) when i am trying to execute the run method of the runnable the run method gets executed almost 9 out of 10 times but there is that 1 time when it doesn't get executed.

mUIHandler.post(uiRunnable) --> does it not always guarantee to execute the run method present in the runnable?

I even added log methods to check and could see that the logs till the post method innvocation gets executed but the run method logs don't get displayed.

How does the post(runnable) work internally? does it guarantee that the ui thread(thread with the handler) will excute this as soon as post is invoked?

Any help would be appreciated.

Thanks!

like image 428
Deva Avatar asked Feb 09 '12 17:02

Deva


2 Answers

I've run into this problem as well on Android 2.2, in my case both Runnables and Messages were being used with the same Handler.

After looking at the Handler source code, it turns out that removing messages with a 'what' value of 0 also removes all queued Runnables. This happens because in the Handler class a Runnable is internally posted as a message with a 'what' value of zero, which are all removed by any call to removeMessages(0). Therefore, avoid using zero as message id.

like image 70
Jesse Avatar answered Oct 07 '22 00:10

Jesse


I have never seen a Handler not properly run the posted runnable. Some things to investigate:

  1. Is there any logic that might result in a race condition between data the thread could be potentially interacting with while the UI-thread runnable is executing?
  2. Do you have a try/catch anywhere that might be silently eating an exception?

My vote (without having seen your code) is that it's probably #1. You wouldn't be the first person to fall victim to hard-to-track-down race conditions as a result of concurrent logic.

like image 36
MattC Avatar answered Oct 07 '22 00:10

MattC