Snake
Snake

Reputation: 14658

Will intentService result in concurrecny issue with the activity

I have read that IntentService create worker thread for the work to be done. If I understand correctly, then that means that the work will be done on a thread other than the UI thread. My question is

if my activity is trying to update shared preferences and this intentService is also updating shared preferences then that means I will run into concurrency issue. Correct? So I better user Service as opposed to IntentService as it runs on Main UI thread

Please confirm if my understanding is correct

Upvotes: 1

Views: 153

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007266

I have read that IntentService create worker thread for the work to be done. If I understand correctly, then that means that the work will be done on a thread other than the UI thread.

Correct.

if my activity is trying to update shared preferences and this intentService is also updating shared preferences then that means I will run into concurrency issue. Correct?

AFAIK, SharedPreferences is thread-safe. So, it will depend a bit on what these two components are updating. If they are updating values under separate keys, AFAIK you should be OK. If, however, they might be modifying values for the same keys, then you may have issues (dirty reads and whatnot).

So I better user Service as opposed to IntentService as it runs on Main UI thread

In Java, objects do not "run" on threads. Methods run on threads. Hence, a service does not run "on Main UI thread". The lifecycle methods for all services (e.g., onCreate(), onStartCommand()) are called on the main application thread. This includes IntentService. IntentService happens to have a built-in implementation of onStartCommand() that routes the Intent to a background thread.

Beyond that, do not do disk I/O on the main application thread, which includes writing to SharedPreferences.

If you may be writing to the same keys on SharedPreferences from multiple threads, use concurrent programming techniques. Java threading has been around about as long as Java has, and there is a lot written about how to do proper concurrent programming in Java.

Upvotes: 2

Related Questions