yahoo / squidb

SquiDB is a SQLite database library for Android and iOS
https://github.com/yahoo/squidb/wiki
Apache License 2.0
1.31k stars 132 forks source link

Thread safety #53

Closed MFlisar closed 9 years ago

MFlisar commented 9 years ago

Is there any thread safety handling integrated that can be somehow enabled? I think not, so is it considered to be integrated one day?

jdkoren commented 9 years ago

Currently there isn't anything that's not provided by the Android SDK already. Is there something specific you have in mind?

sbosley commented 9 years ago

Are you referring to DB read/write operations or to thread safety of things like Query and model objects? The former are thread safe as long as your instance of AbstractDatabase is a singleton.

MFlisar commented 9 years ago

Actually, for my use case I would need thread safety between processes... At least for read/write options... Best would be thread safe transactions...

So in this case, the singleton can't be shared...

sbosley commented 9 years ago

So if I understand correctly, you have two distinct processes that share a single database? I think that's a different issue than simple thread safety, and probably not something we'll be addressing any time soon.

You can read the accepted answer on this StackOverflow post for why it's best to keep your database instance a singleton. If you have multiple open connections to the same database, concurrent writes may fail. AbstractDatabase is a wrapper around SQLiteOpenHelper, so the same principles apply.

If you're currently using SQLiteDatabase and SQLiteOpenHelper to access a single db from multiple processes, presumably you've already had to solve this issue, so you could probably just apply the same synchronization mechanisms that work for you to any squidb database access you do from the various processes. However, you could take another approach and have one process be the database "owner", and make calls to that process via a service binding or something like that rather than trying to share the singleton. SquiDB models are Parcelable, so you could even pass them across process boundaries.

Does that help at all?

MFlisar commented 9 years ago

Yes. I have a long running service (that displays floating UI elements) and a setting activity. I update the service on every single change in the settings, so it sometimes is slow and therefore I decided to split both things into different processes...

I'm already using something like your second suggestion to hand on bus events to another processes and probably i'll take that approach.

sbosley commented 9 years ago

Cool. If the second approach sounds like it will work for you, it's definitely what I would recommend in this instance. I'm going to close this issue, but please feel free to reopen it if you have any more questions about this topic!