Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: is ContentResolver instance thread-safe?

We all know that ContentResolver queries shouldn't be executed on UI thread, but, surprisingly, I can't find information about thread-safety of ContentResolver class in the official docs.

I know how to write thread-safe ContentProvider, and I know that SQLite is thread safe by default (it implements internal locking mechanism).

But, is it safe to use a single instance of ContentResolver from multiple threads (e.g. two treads call insert() or query() on the same object in parallel)?

like image 209
Vasiliy Avatar asked Oct 18 '22 19:10

Vasiliy


1 Answers

Digging a little into the source code we end up finding the ContentResolver instance created by android for an application being an instance of ApplicationContentResolver class residing inside ContentImpl.

As one can see from the snippet below and the source of ContextResolver there are no state variables.

 private static final class ApplicationContentResolver extends ContentResolver {
        private final ActivityThread mMainThread;
        private final UserHandle mUser;
        public ApplicationContentResolver(
                Context context, ActivityThread mainThread, UserHandle user) {
            super(context);
            mMainThread = Preconditions.checkNotNull(mainThread);
            mUser = Preconditions.checkNotNull(user);
        }
    ....

This would imply necessarily that its thread safe.

like image 162
humblerookie Avatar answered Oct 21 '22 06:10

humblerookie