Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android sqlite concurrency without exceptions

Tags:

android

sqlite

Sqlite on android lets you access the database from multiple procs for reads, but if you're currently writing from one process, reads and writes from other procs will throw an exception because the first write has a lock on the db.

By "procs" I mean other threads in the same app.

Is there a standard way to have the other threads simply wait until the database is available again, possibly with a specified timeout, rather than throwing an exception?

Anticipating the "why are you doing it that way?" answers, its just the way we're doing it, and that's it. We're also not going to use a content provider. Just want a way to synchronize db access.

Assuming there's no standard way to do it, we'll probably wind up writing a wrapper around the db calls to do some thread synchronization.

like image 854
Kevin Galligan Avatar asked Aug 31 '10 14:08

Kevin Galligan


2 Answers

So long as you're using the same SQLiteDatabase object, the synchronisation is done for you.

So if you access the object via a singleton, there should be no problem. Though you may want to add some further logic if you want to implement a timeout, e.g. wait/notify or something similar.

like image 66
Christopher Orr Avatar answered Dec 07 '22 08:12

Christopher Orr


Or you can use another database that does support it, like H2. I know it may sound like a strange idea. But according to my initial test it works well (on the emulator as well as on the device), and is actually not slower. Except for opening and closing a database, which is currently quite slow, about 1 second, but that has other reasons, and hopefully will get fixed in the next version.

like image 23
Thomas Mueller Avatar answered Dec 07 '22 06:12

Thomas Mueller