It depends which thread is callling the code-snippet you show above (the 
one calling 'removeMessage').

If your code, calling 'removeMessage', is run on the same thread that is 
tied to the *handler*, you're fine. The message you sent will not be 
handled/run until your code finishes first. No extra work necessary.

If your code, calling 'removeMessage' is run on another thread than the one 
tied to the *handler*, you need to sync it up. This could be as simple as 
send another message on that handler that will call 'removeMessage': E.g.:
handler.post(new Runnable() {
  public void run() {
    // Right now, calling 'removeMessages', etc. is done
    // on the handler's thread as well.
    handler.removeMessages(MSG_ONE);
    handler.removeMessages(MSG_TWO);
    ...

    if (conditionOne)
      handler.sendEmptyMessageDelayed(MSG_ONE, timeoutOne);

    if (conditionTwo)
      handler.sendEmptyMessageDelayed(MSG_TWO, timeoutTwo);    
  }
});

Since both the 'removeMessages' and 'sendEmptyMessageDelayed' are called on 
'handler' the Runnable needs to finish first before any other message sent 
to 'handler' can be executed.


On Tuesday, October 30, 2012 9:17:39 AM UTC-4, Jay Howard wrote:
>
> I'm using a timer to manage timeout events, and would like to ensure that 
> a particular method runs atomically without the handler issuing messages 
> while the method is executing.  Its basic form is:
>
> handler.removeMessages(MSG_ONE);
> handler.removeMessages(MSG_TWO);
> ...
>
> if (conditionOne)
>   handler.sendEmptyMessageDelayed(MSG_ONE, timeoutOne);
>
> if (conditionTwo)
>   handler.sendEmptyMessageDelayed(MSG_TWO, timeoutTwo);
>
> ...
>
> What I want to avoid is a situation where, before the removeMessages() 
> calls execute, one of the messages reaches its timeout and is delivered to 
> the message queue, then I send a duplicate one immediately after.  My goal 
> is to guarantee that there is never more than one of each message type "in 
> flight" on the handler at any given time.
>
> Does the Handler class synchronize on MessageQueue when delivering its 
> messages?  If so, then could I just synchronize on the MessageQueue?  Or 
> would that be a terrible idea, since it's used by entities other than just 
> my Handler?
>

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to