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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值