Which thread runs ContentProvider?

Torstein I. Bø picture Torstein I. Bø · Aug 16, 2010 · Viewed 12.5k times · Source

If I call to a ContentProvider from a Activity, which thread is ContentProvider running in?

E.g. What happens if the Activity is killed and a query is executing in the ContentProvider? Say that you have a slow network query f.ex.

Answer

satur9nine picture satur9nine · Aug 26, 2010

If you mean the normal use case of using a ContentResolver to call a ContentProvider then here is what happens according to the best of my knowledge:

  1. I am assuming in this example that your ContentProvider lives in one process and your Activity in another process.

  2. If the ContentProvider has not been created then the onCreate() method is called using the "main" thread of the application's process.

  3. The query()/insert()/update()/delete() methods are called using BinderThreads that sit around in every application process waiting for incoming commands from other processes.

So what happens if the Activity that triggered the query()/insert()/etc is killed in the middle of one of these method calls? I can't say for certain but I'm fairly confident that whatever is happening in the ContentProvider will continue because the ContentProvider process should go on unaffected but what happens after that method returns I can't say for certain.

I'm not sure how a slow network would be involved in this at all unless your content provider is backed by a network instead of the usual sqlite db?

Clarification:

There are two possibilities when invoking a ContentProvider function (query/insert/update/delete/etc):

  1. Your ContentProvider is in the same process as the caller. If so the ContentProvider function runs synchronously on the same thread as the caller.

  2. Your ContentProvider is in a different process as the caller. If so the ContentProvider function runs on a binder thread in the ContentProvider process.

In both cases the the caller is blocked until the ContentProvider function returns. As always read the full documentation from Google and/or the AOSP source code.

http://developer.android.com/reference/android/content/ContentProvider.html http://developer.android.com/guide/topics/providers/content-provider-basics.html http://developer.android.com/guide/components/processes-and-threads.html