0

I'm implementing Android Backup Service and the guide says that

reading and writing to external storage is not threadsafe

It then says that the onBackup and onRestore functions should be performed in a synchronized statement. My question is: do I need to use this approach everywhere I read/write my database?

So

db.open();
course = db.getCourse(courseId);
db.close();

would become...

synchronized(MyConstants.DBContant){
    db.open();
    course = db.getCourse(courseId);
    db.close();
}

I read/write to my db a lot. I want to make sure before I go add this everywhere.

NSouth
  • 5,067
  • 7
  • 48
  • 83
  • 1
    `SQLiteDatabase` is thread-safe, and doesn't need explicit synchronization on concurrent access. – corsair992 Nov 25 '14 at 02:49
  • @corsair992, Even if another service is accessing the file in a method which is not thread-safe? If the backup service tries to access the file while it's being edited, it will be blocked? – NSouth Nov 25 '14 at 02:52
  • 1
    Whether it will be blocked or not depends on whether your transaction is exclusive or immediate, and whether you have write-ahead logging enabled or not - either way it would be atomic and thread-safe. Currently, the connection pool used by `SQLiteDatabase` only allows a maximum of one concurrent connection though, so it will always be blocked in the current semantics. – corsair992 Nov 25 '14 at 03:04
  • I don't alter the default write-ahead logging and I don't know if my transactions are exclusive or immediate. I query to read from my db and I use SQLiteDatabase's `insert` method to create new rows. But it sounds like I should be safe even if an external process is trying to read/write the database. – NSouth Nov 25 '14 at 03:22
  • 1
    SQLite statements outside of an explicit transactions implicitly start a deferred transaction which will be committed after all the current reads and writes are completed. Write-ahead logging is disabled by default on AOSP, but it wouldn't make any difference in this case. Actually, SQLite's own locking mechanism seems to be based on a fail mechanism instead of wait, which is probably the reason why the Android `SQLiteDatabase` only allows one connection at a time (the rest are deferred). In the case of inter-process access, you might have to handle concurrency yourself though. – corsair992 Nov 25 '14 at 04:27

0 Answers0