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?
Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.
RoomDatabase wraps the standard SQLiteDatabase , which is fairly thread-safe, with all work being done in transactions.
Use type converters You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.
This article describes how to define the relationship between entities in the Room persistence library. Because SQLite is a relational database, entities can be related to one another.
RoomDatabase
wraps the standard SQLiteDatabase
, which is fairly thread-safe, with all work being done in transactions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With