views:

42

answers:

2

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.

+1  A: 

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.

Christopher
So, you're saying use 1 SQLiteOpenHelper, and then 1 writable connection for your whole app? All activities and services?
kāgii
I don't have enough "clout" to thumb up this answer, but it did lead me down the path to the right answer. SQLiteOpenHelper actually returns the same cached object, regardless if you call "getReadable..." or "getWritable...", then the database object itself has a java Lock object to make sure any call, read or write, is serialized. I'm going to have to keep a singleton SQLiteOpenHelper, which will let me periodically "close" the db objects, which seems "safer".Sqlite itself can handle multiple read clients, which would logically seem to perform better, but whatever.Thanks again.
kāgii
@kāgii as the question asker, you could accept this answer, or write up your own answer and accept that
ohhorob
I've learned quite a bit since asking. Here's my blog post about it. This answer is correct, but you can actually share the same sqliteopenhelper instance in your app.http://www.kagii.com/journal/2010/9/10/android-sqlite-locking.html
kāgii
A: 

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.

Thomas Mueller