开发者

Android sqlite concurrency without exceptions

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 databas开发者_JS百科e 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜