Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an IntentService's onStartCommand(..) method thread safe?

I have an IntentService class that can be started from various places in a complex application - Activities, background Threads, other Services. I'd like to keep a counter of how many times the service was invoked. I use a private int variable within my IntentService class to keep track of that, I increment it from my onStartCommand(...) method.

It just occured to me, as the onStartCommand(...) method can be called from various asynchronous threads, that this might not be a thread-safe solution. So the question is, do I need to wrap the access to this counter variable in a synchronized block, or does the IntentService implementation of onStartCommand(...) takes care of this for me?

As a note, I know I could safely increment the variable from onHandleIntent(...), but I'd need a count on the actual requests and not on the executed intents.

like image 332
András Szepesházi Avatar asked Jun 24 '12 07:06

András Szepesházi


1 Answers

It just occured to me, as the onStartCommand(...) method can be called from various asynchronous threads, that this might not be a thread-safe solution.

onStartCommand() is always called on the main application thread in any service. You cannot be called with onStartCommand() in two threads simultaneously.

like image 134
CommonsWare Avatar answered Sep 20 '22 00:09

CommonsWare