Is the IntentService onStartCommand (..) method thread safe?

I have an IntentService class that can be run from different places in a complex application - Activities, Background Threads, other Services. I would like to keep a counter of how many times the service was called. I use the private int variable in the IntentService class to track this, I increase it using the onStartCommand (...) method.

It just happened to me, since the onStartCommand (...) method can be called from different asynchronous threads, that this may not be a thread safe solution. So the question is, should I wrap access to this counter variable in a synchronized block, or will the IntentService implementation for onStartCommand (...) take care of this for me?

As a note, I know that I can safely increment the variable from onHandleIntent (...) , but I will need to count the actual requests, and not according to the intent.

+6
source share
1 answer

It just happened because the onStartCommand (...) method can be called from different asynchronous threads, which may not be a thread safe solution.

onStartCommand() always called in the main thread of the application in any service. You cannot call with onStartCommand() on two threads at the same time.

+14
source

Source: https://habr.com/ru/post/918858/


All Articles