views:

85

answers:

1

I'm wondering whether prepared statements in Android (instances of SQLiteStatement) are thread-safe. In particular I'm asking with regard to the following scenario:

In a ContentProvider you create a pre-compiled insert statement during onCreate. Then, in the overriden insert method you make use of this statement by binding a set of parameters to it and calling executeInsert on it.

We know that a ContentProvider has to be written in a thread-safe manner. If SQLiteStatement does not bind parameters per thread, a concurrent call to the provider's insert method would alter the statement's bindings and result in unpredictable behavior.

Android's own Contacts provider uses prepared statements in this way (http://bit.ly/bDuKAT), so I tend to believe that they are in fact thread-safe. Looking at the source code of SQLiteStatement I don't see how though (http://bit.ly/9M1Swv).

So, is SQLiteStatement (or SQLiteProgram that is) thread-safe with respect to parameter binding or not?

+1  A: 

If it's two separate methods, then it can't possibly be thread-safe:

mStatusUpdateDelete.bindLong(1, dataId);
mStatusUpdateDelete.execute();

The first thread could call bindLong with 1, then the second thread with 2, and then both threads could call execute. So even if bindLong and execute internally are thread safe, it wouldn't help.

Thomas Mueller
That's generally the case, yes. However, it could still be thread-safe if SQLiteStatement's structure in which the binding is kept is of type ThreadLocal<?>. In this case SQLiteStatement would have a per-thread binding. In the particular case of SQLiteStatement all parameter binding is delegated to a native SQLite interface of which I don't know the inner workings. If it is not thread-safe (of which we are both pretty sure), I wonder how the Contacts provider deals with this issue.
js