我可以在Android上的多个线程中使用相同的RoomDatabase对象吗? [英] Can I use the same RoomDatabase object from multiple threads on Android?
问题描述
我在Android上使用Room persistence库。目前,每次访问数据库时都会有一些额外的同步代码。我想知道这段代码是否必要。
I'm using the Room persistence library on Android. Currently, I have some extra synchronization code each time I access the database. I want to know if this code is necessary.
我目前以单身人士的身份访问数据库。
这就是我当前将对象插入数据库的方式:
I currently access the database as a singleton. This is how I am currently inserting objects into the DB:
// Insert values into DB
final AppDatabase db = AppDatabase.get(this);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
synchronized (db) {
for (WorkOrder wo : workOrderList) {
db.workOrderDao().insertAll(wo);
}
}
}
});
我是否需要在同步块中插入代码?
Do I need to have the insertion code in a synchronized block?
推荐答案
RoomDatabase
包装标准 SQLiteDatabase
,其中是相当线程安全的,所有工作都在交易中完成。
RoomDatabase
wraps the standard SQLiteDatabase
, which is fairly thread-safe, with all work being done in transactions.
我不会担心 synchronized
等等关于交易,就像现在一样,这项工作是在N个交易中完成的(每个一个WorkOrder
)。我会有一个 insertAll(List< WorkOrder>)
,因此您可以在一个事务中执行此操作。或者,如果由于某种原因不切实际,请使用 @Transaction $ c $将循环移动到
@Dao
类中。 c>注释,表示整个方法应在单个事务中执行。
I would worry less about synchronized
and more about transactions, as right now, this work is being done in N transactions (one per WorkOrder
). I would have an insertAll(List<WorkOrder>)
, so you can perform this in one transaction. Or, if for whatever reason that's impractical, move your loop into the @Dao
class in its own method, with a @Transaction
annotation, to indicate that the entire method should be performed in a single transaction.
这篇关于我可以在Android上的多个线程中使用相同的RoomDatabase对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!