Writing and reading between threads with Android Realm

筅森魡賤 提交于 2019-12-07 04:12:40

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28134130/writing-and-reading-between-threads-with-android-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!