Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use the same RoomDatabase object from multiple threads on Android?

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?

like image 286
Jonathan Seaman Avatar asked Nov 28 '17 06:11

Jonathan Seaman


People also ask

What will happen if multiple threads accessing the same resource?

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.

Is Room is thread safe Android?

RoomDatabase wraps the standard SQLiteDatabase , which is fairly thread-safe, with all work being done in transactions.

What is TypeConverter in Android?

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.

Is Room database relational?

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.


1 Answers

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.

like image 124
CommonsWare Avatar answered Sep 20 '22 23:09

CommonsWare