contentProvider不是线程安全的

A common source of confusion when implementing ContentProviders is that of thread-safety.We all know that any potentially expensive query should be asynchronous so as not to blockthe UI thread, but when, if ever, is it OK to make calls to the ContentProvider frommultiple threads?

Threads and Content Providers

The documentationon ContentProviders warns that its methods may be called from multiple threads and thereforemust be thread-safe:

Data access methods (such as insert(Uri, ContentValues) and update(Uri, ContentValues, String, String[])) may be called from manythreads at once, and must be thread-safe.

In other words, Android does not synchronize access to the ContentProvider for you.If two calls to the same method are made simultaneously from separate threads, neithercall will wait for the other. Requiring the client to deal with concurrency themselvesmakes sense from a framework developer's point of view. The abstract ContentProvider classcannot assume that its subclasses will require synchronization, as doing so would behorribly inefficient.

Ensuring Thread Safety

So now that we know that the ContentProvider is not thread safe, what do we need todo in order to eliminate potential race conditions? Just make every methodsynchronized, right?

Well... no, not necessarily. Consider a ContentProvider that uses a SQLiteDatabaseas its backing data source. As per thedocumentation,access to the SQLiteDatabase is synchronized by default, thus guaranteeing thatno two threads will ever touch it at the same time. In this case, synchronizingeach of the ContentProvider's methods is both unnecessary and costly. Rememberthat a ContentProvider serves as a wrapper around the underlying data source;whether or not you must take extra measures to ensure thread safety often dependson the data source itself.

Conclusion

Although the ContentProvider lacks in thread-safety, often times you will find thatno further action is required on your part with respect to preventing potentialrace conditions. The canonical example is when your ContentProvider is backed bya SQLiteDatabase; when two threads attempt to write to the database at the sametime, the SQLiteDatabase will lock itself down, ensuring that one will wait untilthe other has completed. Each thread will be given mutually exclusive access to thedata source, ensuring the thread safety is met.

ref:http://www.androiddesignpatterns.com/2012/10/sqlite-contentprovider-thread-safety.html

上边作者说到CONTENT PROVIDERS 的实现没有考虑线程安全,所以访问content provider时要确保不要多个线程同时去访问。如果多个线程同时访问数据库自己会加锁,不会造成数据丢失,但可能会报数据库被锁的exception.

你可能感兴趣的:(android)