Is SQLiteDatabase thread safe?


#1

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.


#2

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.


#3

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


#4

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.


#5

Thanks for the quick reply!


#6

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).


#7

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


#8

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 https://sqlite.org/wal.html ?

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.