SQLiteDatabase multi-thread locking pattern SQLiteDatabase multi-thread locking pattern sqlite sqlite

SQLiteDatabase multi-thread locking pattern


In SQLite, there can be arbitrarily many readers, but any writer blocks all other readers and writers.

You have to use a single lock for both readers and writers.

Please note that locks must be held as long as you're actually accessing the database.


If you want to support multiple readers, use a lock that implements ReadWriteLock, such as ReentrantReadWriteLock. Something like this:

class MyData {    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();    private final Lock r = rwl.readLock();    private final Lock w = rwl.writeLock();    public Data ReadSomething(int id) {        r.lock();        try {            Cursor c = readableDatabase.query(...);            return c.getString(0);        } finally {            r.unlock();        }    }    public void ChangeSomething(int id, int value) {        w.lock();        try {            writeableDatabase.update(...);        } finally {            w.unlock();        }    }}