I still haven't really wrapped my head around synchronization. I know it's there, I know why it's used and what the idea is behind it, but Im lacking the practical skill and real world examples to understand exactly how it works and how it's implemented when several activies are trying to read/write to the database at the same time. Do you share your objects through Application, or is the system intelligent enough to synchronize various objects of the same type?
Perhaps a Content Provider is a better way to go as I understand that has built in sync.
I digress though.
Im still confused over database activity. Remember that I have a service running every 60 seconds in the background reading the same table an update function is writing to. Yes Im looking to change this, but right now I want to understand database handling in Android more and work out what's happening.
If I have a loop such as:
db = provider.get开发者_如何学PythonReadableDatabase();
while(theres_still_work_today) {
do_some_calculations;
update_database;
}
provider.close();
this works fine as a standalone. If I try and place this in a thread, I get errors galore about locking. But when run like this:
while(theres_still_work_today) {
do_some_calculations;
db = provider.getReadableDatabase();
provider.close();
update_database;
}
I find that bizarrely, this actually seems faster, and gives no locking issues.
Am I just being incredibly lucky that I don't get two events triggering at the same time causing a lock? Is there some kind of timeout built into database handling in Android/SQLite?
I don't understand why the last bit of code should work OK, and why it should work faster?
Im not entirely confident about the Android Emulator though. If I use the first option with a single open/close outside the loop, sometimes I can get through a long long loop fine even though the service triggers in the background.
Other times it crashes on a whim.
I also don't know why "isDatabaseLockedByOtherThreads()" does not report that it is locked by other threads.
Any advice?
Thanks Simon
精彩评论