Can Two Asynctasks Share The Same Sqlitedatabase Object?
Solution 1:
All of your threads in your application should use the same database object -- even if reading and writing simultaneously. SQLite handles this with internal locking mechanisms appropriately.
What you don't want to do is to use multiple database objects to read and write from a database. That may result in inconsistent data.
See here:
The last link is a good one. To quote Kevin Galligan:
- Sqlite takes care of the file level locking. Many threads can read, one can write. The locks prevent more than one writing.
- Android implements some java locking in SQLiteDatabase to help keep things straight.
- If you go crazy and hammer the database from many threads, your database will (or should) not be corrupted.
Here’s what’s missing. If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.
As an aside, Kevin has done a good bit of the work of the Android side of ORMLite, my Java ORM package that supports Android.
Post a Comment for "Can Two Asynctasks Share The Same Sqlitedatabase Object?"