5
votes

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)?

2
I think you must have moved on, but for people who land up here it all depends on the underlying backing store, came across this wonderful article on the same androiddesignpatterns.com/2012/10/… - humblerookie
@humblerookie, the article is correct - SQLite implements internal locking, therefore implementations of ContentProvider backed by SQLite are thread safe. However, my question concerns ContentResolver and not ContentProvider - is ContentResolver objects returned by getContentResolver() calls are thread safe. While these questions seem similar, they are really two completely different questions. - Vasiliy
Apologies for being ignorant :/ . However Just decided to take a look at the Content resolver object created by android. Seems like its an instance of ApplicationContentResolver android.googlesource.com/platform/frameworks/base/+/56a2301/… As one can observe this class does not maintain state variables. So seems like the resolver object is indeed thread safe. - humblerookie
@humblerookie, if you have already investigated the source, why not publishing your findings as an answer? - Vasiliy
Surely. Will do - humblerookie

2 Answers

4
votes

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.

-1
votes

It depend on your code ,if you implment your contentResolver in the safe single instance that may be safe if you didn't add the lock ,it will not thread safe.