Is SQLiteDatabase thread safe?

If our Android application has single instance of SQLiteDatabase, and we have different jobs doing the database operation with SQLiteDatabase at the same time, is it thread safe?

Thanks.

Hello @AlbertWangCa

SQLCipher for Android is compiled with -DSQLITE_THREADSAFE, however while the wrapping Java library contains some threading primitives for certain operations, is not entirely thread safe. It is recommended that you include a synchronization mechanism to allow for coordinated access to your connection.

I saw there’s lock method in SQLiteDatabase java class, so it’s still not thread-safe? Thanks.

Hello @AlbertWangCa

We recommend you include a synchronization mechanism within your application as not all operations within the client library have the necessary facilities in place to be considered thread-safe.

Thanks for the quick reply!

I received a question by email if the MultiThreadReadWriteTest should need synchronized access to parallel database reader and writer access handles in order to work (pass) in a proper and consistent manner (in reference to my observation in sqlcipher/android-database-sqlcipher#176). I think the answer is that this is not an issue (no synchronized access needed) because the reader and writer access objects use separate SQLiteDatabase instances, using separate sqlite3.c database connections.

This is a characteristic of the Android SQLite database API in general, I think not clear enough for non-experts. I would like to see this documented better (someday).

Thanks for following up. Since the test is configured with “DatabaseAccessType.Singleton” do the reader and writeer share the DB instance ?

if (accessType == DatabaseAccessType.Singleton) {
if (instance == null) {
instance = SQLiteDatabase.openOrCreateDatabase(databaseFile, password, null); }
return instance;
}

Is characteristic of Android DB you are referring to - is this just a sqlite feature for a while https://sqlite.org/wal.html ?

Thanks

Hi @rdseth

Since the test is configured with “DatabaseAccessType.Singleton” do the reader and writeer share the DB instance ?

That specific test is configured to utilize a shared database instance between the readers and writers through synchronized access.

Is characteristic of Android DB you are referring to - is this just a sqlite feature for a while Write-Ahead Logging ?

The WAL journal mode is a separate mechanism for managing atomic commits and rollbacks within the database and is not specific to Java. You can use WAL mode within SQLCipher for Android by adjusting the PRAGMA journal_mode.