reis_eliel
reis_eliel

Reputation: 328

OrmLite multiple databases being written concurrently

I have used the "HelloTwoDbs" example in OrmLite examples for Android to check the usage of double databases at the same time.

Assuming i have multiple databases setup with OrmLite, can i write in both different databases concurrently with no problems? Its only "one thread write at a time" for each database, but both writes threads (one for each database) would be executing concurrently.

I actually tested this in one emulator with the code bellow and had no problems, but still i am insecure if it is actually really supported by OrmLite and would not cause me future problems.

btw, i am inclined to use the two different databases approach because i want to do a small social interaction app, and i would like to dettach user generated content from application static content for a few reasons, mainly because user generated content gets synced and modified way to faster then application static content does. Also, with two databases i could actually update both contents at the same time concurrently from different sources to different databases, or so i hope.

Please, if possible, help me. =)


Small test i did based on the site example, just calling "doOtherStuff" on the HelloTwoDbs.java:

Added ->

private void doOtherStuff() {

new Thread(new Runnable() {
    @Override
    public void run() {
        Log.e(LOG_TAG, "Started 1");

        final DatabaseHelper1 databaseHelperA = getHelper1();

        try {

            final Dao<SimpleData, Integer> simpleDao = databaseHelperA.getSimpleDataDao();

            for (int i = 0; i < 5000; i++) {
                Log.e(LOG_TAG, "Adding (1): " + i);
                simpleDao.create(new SimpleData(i));

            }
        } catch (SQLException e) {
        }
    }
}).start();

new Thread(new Runnable() {
    @Override
    public void run() {
        Log.e(LOG_TAG, "Started 2");

        final DatabaseHelper2 databaseHelperB = getHelper2();

        try {

            final Dao<ComplexData, Integer> complexDao = databaseHelperB.getComplexDataDao();

            for (int i = 0; i < 5000; i++) {
                Log.e(LOG_TAG, "Adding (2): " + i);
                complexDao.create(new ComplexData(i));

            }
        } catch (SQLException e) {
        }
    }
}).start();
}

Upvotes: 0

Views: 1014

Answers (1)

Gray
Gray

Reputation: 116908

Assuming i have multiple databases setup with OrmLite, can i write in both different databases concurrently with no problems?

I would think so, yes. Really you can write using multiple threads to a single database. SQLite does database level locking so the 2nd thread will wait until the first operation finishes.

The only time you will get into problems if you have multiple connections open to the same database. You will get data corruption if this is the case.

Upvotes: 1

Related Questions