In other words, to my understanding, this is not thread safe (for multiple calls of startService()
):
public class RaceService extends Service {
volatile int a; // edit: added volatile to clarify my point
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
a++;
Log.w("RaceService", "a: " + a);
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
}
because there is only one instance of the service created (although never managed to find a clear assertion for this - if anyone could point me to the source where the service is actually instantiated (by reflection?) I would appreciate it). If one instance were created per startService()
this would just print 1 on every call of startService.
But is this:
public class RaceService2 extends Service {
int a;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
a++;
Log.w("RaceService2", "a: " + a);
return super.onStartCommand(intent, flags, startId);
}
}
thread safe (for multiple calls of startService()
) ?
Would using an IntentService make a difference in these two examples (where the code would be in onHandleIntent()
) ?