简体   繁体   中英

Android - sqlite content providers and multithreading

I'm a little confused about content providers. If I have multiple activities in my application do they each get their own instance of the content provider? it's just essentially a class/interface?

In one activity I will have many threads simultaneously writing to the database. How do I deal with allowing one thread to write at a time?

Do I just catch SQLiteDatabaseLockedException, put the thread to sleep then retry? Or is there a better way?

Are the database locks released when an activity pauses/is destroyed? If so could I just create a synchronized lock against the content provider itself?

If you work directly with databases and have multiple writers from different threads you may run into concurrency issues.

The ContentProvider can be accessed from several programs at the same time, therefore you must implement the access thread-safe. The easiest way is to use the keyword synchronized in front of all methods of the ContentProvider , so that only one thread can access these methods at the same time.

If you do not require that Android synchronizes data access to the ContentProvider , set the android:multiprocess=true attribute in your <provider> definition in the AndroidManifest.xml file. This permits an instance of the provider to be created in each client process, eliminating the need to perform interprocess communication (IPC).

Oops, I lost my unregistered user cookie so can't vote Femi's answer correct.

The documentation http://developer.android.com/guide/topics/providers/content-providers.html confirms this with "When a query is initiated, the Android system identifies the content provider that's the target of the query and makes sure that it is up and running. The system instantiates all ContentProvider objects; you never need to do it on your own. In fact, you never deal directly with ContentProvider objects at all. Typically, there's just a single instance of each type of ContentProvider. But it can communicate with multiple ContentResolver objects in different applications and processes. The interaction between processes is handled by the ContentResolver and ContentProvider classes. "

If you are using a ContentProvider, I believe you don't care how many threads are reading/writing: the Android platform handles marshalling all your calls onto a single thread and sorting out synchronization and locking. You just open your database and read/write into it, and everyone else talks through the ContentProvider interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM