Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Android Context thread safe?

Tags:

android

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.

like image 747
dan Avatar asked May 15 '12 10:05

dan


People also ask

Is SharedPreferences thread-safe?

The SharedPreferences implementation in Android is thread-safe but not process-safe. Normally your app will run all in the same process, but it's possible for you to configure it in the AndroidManifest.

What is thread-safe android?

By design, Android View objects are not thread-safe. An app is expected to create, use, and destroy UI objects, all on the main thread. If you try to modify or even reference a UI object in a thread other than the main thread, the result can be exceptions, silent failures, crashes, and other undefined misbehavior.

Is Android service a thread?

Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. You should run any blocking operations on a separate thread within the service to avoid Application Not Responding (ANR) errors.

What is Android content context?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).


1 Answers

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.

like image 140
Janusz Avatar answered Oct 06 '22 13:10

Janusz