Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing and reading between threads with Android Realm

I'm performing some investigation of Realm threading and encountered issue.

In this simple example I have 2 Thread objects, one for writing and second one for reading. The reader Thread gets count of written objects always as 0, but inside writer scope the size() for items in DB is correct. When I relaunch app, the reader gets the first count ok before any insertions.

Thread writer = new Thread() {

    @Override
    public void run() {
        while (mRunning) {
            try {
                Realm r = Realm.getInstance(context, "test_db");
                r.beginTransaction();

                TestData data = r.createObject(TestData.class);

                r.commitTransaction();

                Logger.e("WRITER THREAD COUNT: " + 
                    r.where(TestData.class).findAll().size());

                sleep(LATENCY);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

writer.setPriority(Thread.MAX_PRIORITY);
writer.start();

Thread reader = new Thread() {

    @Override
    public void run() {
        while (mRunning) {
            try {
                Logger.e("READING THREAD COUNT: " + Realm.getInstance(context,
                        "test_db").where(TestData.class).findAll().size());

                sleep(LATENCY);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
};

reader.setPriority(Thread.MAX_PRIORITY);
reader.start();

Is there something needed to do for this to work?

Thanks.

like image 513
Niko Avatar asked Jan 25 '15 07:01

Niko


1 Answers

Emanuele from Realm here.

What you are describing is expected behavior :) Since the reader thread doesn't have a Looper, it has no way to receive notifications from the reader thread and will never update unless you manually execute a refresh.

In out repo we have several examples (not to mention unit tests) using threads with and without Looper, illustrating the current best practices.

like image 187
Emanuelez Avatar answered Sep 26 '22 05:09

Emanuelez