4

My Activity consists of a BroadcastReceiver and an AsyncTask, both of them update an ArrayList (very often). I understand that an AsyncTask runs in the background, and there may be a possibility where the BroadcastReceiver and the AsyncTask threads may update the ArrayList at the same time. How can I make them thread-safe ?

EDIT: As alexander mentioned, a BroadcastReceiver is run on the main thread unless you explicitly implement it otherwise.

4
  • 1
    developer.android.com/reference/java/util/Vector.html <<< this Commented Sep 15, 2014 at 12:34
  • try creating a queue structure Commented Sep 15, 2014 at 12:34
  • Unless you show us the code (in both threads) that access and update the list, it is not possible to give a reliable answer. (There are various methods that might work ...) Commented Sep 15, 2014 at 12:49
  • Try to make it accessible only once at any point. Store/Queue any other incoming changes. Of course, this makes only sense depending on the importance of an immediate change. A very naive approach would be make a static variable and change it everytime something is changed and this is also the condition under which your ArrayList can be changed. Maybe there is a better way, but this should work. This Problem also exist with e.g. a StringBuilder and a BufferedStringBuilder (BufferedStringBuilder is Threadsecure). Maybe you can find something helpful there... I hope this helps a bit. John Commented Sep 15, 2014 at 12:57

1 Answer 1

2

AsyncTask runs as a separate thread. A BroadcastReceiver usually runs on the main thread, unless you specify otherwise in 'registerReceiver' (see here: http://developer.android.com/reference/android/content/Context.html#registerReceiver(android.content.BroadcastReceiver,%20android.content.IntentFilter,%20java.lang.String,%20android.os.Handler) )

You can either use a Vector as Budius wrote, or wrap all access to the ArrayList with a synchronized block:

synchronized(myList){
    myList.add(itemToAdd);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I did not know that a BroadcastReceiver ran on the main thread. Nice catch! Also, I decided to go with Vector thanks to Budius.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.