Android的SQLiteStatement(准备好的语句)是线程安全的吗?即“绑定*,绑定*...执行”。原子?
我想知道 Android 中的准备语句(SQLiteStatement 的实例)是否是线程安全的。我特别询问以下场景:
在 ContentProvider 中,您在 onCreate 期间创建预编译的插入语句。然后,在重写的插入方法中,您可以通过将一组参数绑定到该语句并对其调用executeInsert 来使用该语句。
我们知道 ContentProvider 必须以线程安全的方式编写。如果 SQLiteStatement 不为每个线程绑定参数,则对提供程序的 insert 方法的并发调用将改变语句的绑定并导致不可预测的行为。
Android 自己的联系人提供程序以这种方式使用准备好的语句 (http://bit.ly/bDuKAT),所以我倾向于相信它们实际上是线程安全的。查看 SQLiteStatement 的源代码,我不明白如何实现(http://bit.ly/9M1Swv )。
那么,SQLiteStatement(或 SQLiteProgram)对于参数绑定是否是线程安全的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SQLiteStatement 文档中明确指出
,因此,该类不是线程安全的,并且不能被多个线程同时使用而不产生意外结果。
It is explicitly stated in the SQLiteStatement documentation that
Thus, the class is not thread-safe and cannot be used by multiple threads concurrently without unexpected results.
如果它是两个单独的方法,那么它不可能是线程安全的:
第一个线程可以使用 1 调用
bindLong
,然后第二个线程使用 2 调用,然后两个线程都可以调用execute
。因此,即使bindLong
和execute
内部是线程安全的,也无济于事。If it's two separate methods, then it can't possibly be thread-safe:
The first thread could call
bindLong
with 1, then the second thread with 2, and then both threads could callexecute
. So even ifbindLong
andexecute
internally are thread safe, it wouldn't help.