When I use the Android Context within an AsyncTask#doInBackground, is it thread safe? The context is provided via constructor or via getApplicationContext() from a surrounding Activity. This simple questions is asked a lot at stackoverflow and else where but I found not a clear answer?
E.g. in the doInBackground() I use the context in order to Instantiate an DAO class.
@Override
protected Void doInBackground(Void... params) {
ExampleDao dao = new ExampleDao(context);
...
}
I saw several examples doing that in this way, but I cannot image that this is thread-safe, because the context is now accessed by the main tread (UI Thread) and the worker thread.
You can always access the context from different Thread as long as you are not changing something and you only retrieve resources through the context I don’t see a problem with Thread-safety.
The problem is that the context will stay in memory and active as long as the Thread runs. This is a good thing for you because you can rely on having a valid context all the time.
The bad thing is that if you pass an Activity as a context all the views and member variables from this activity will also stay in memory and this can lead to a very late garbage collection for a lot of memory, like Waqas suggested.
On thing I would not do from a different Thread is accessing methods from Context subclasses like setTheme() that will affect the currently displayed views.