Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to pass around the context to multiple threads?

I'm implementing a service that does REST calls for multiple applications. The results of certain REST calls should be stored in a content provider.

I'm currently trying to use multiple threads that would do the HTTP request, parse the result, and store the data in a content provider. In order to do this, I must pass around the Context to each of the threads. I'm not sure if this is a good idea because I do not know if the Context is ok to be passed to multiple threads because of its size, thread safety, etc. I'm thinking that I'm only passing a reference to the Context object for each thread, so maybe its not heavy to pass it around?

like image 995
avendael Avatar asked Sep 01 '25 16:09

avendael


1 Answers

Yes, this is fine. I don't believe that explicit synchronization is required, but many of the interesting things you can do with a Context must happen on the UI thread.

Because of this reason it is usually wise to do your http request inside an AsyncTask, which will arrange to have your implementation of onPreExecute and onPostExecute run on the UI thread, as well as provide a nice interface for cancellation.

like image 84
Matthew Willis Avatar answered Sep 04 '25 04:09

Matthew Willis