简体   繁体   English

从不同线程问题访问的领域数据库对象(仅在某些设备上)

[英]Realm database objects accessed from different thread issue (only on some devices)

I have a singleton class 'RealmDatabaseManager' where i have synchronized methods for reading/writing from realm local database. 我有一个单例类“ RealmDatabaseManager”,其中有用于从领域本地数据库读取/写入的synchronized方法。

The methods look like this: 方法如下:

public long getPendingImagesCount() {
    synchronized (this) {
        realm = Realm.getInstance(RealmUtils.getRealmConfiguration());
        long count = realm.where(PatientRecordImage.class)
                .count();
        realm.close();
        return count;
    }
}

Where this is the instance of singleton class. this是单例类的实例。

These methods are accessed from main as well as worker threads via the singleton instance. 可通过单例实例从主线程和工作线程访问这些方法。 Every method creates and closes it's own realm. 每个方法都会创建并关闭自己的领域。

The code works without issues on the devices i'm testing on but I've received Crashlytics reports from some devices giving two fatal errors. 该代码可以在我正在测试的设备上正常运行,但是我从某些设备上收到了Crashlytics报告,给出了两个致命错误。

IllegalStateException: Realm objects can only be accessed on the thread they were created.

And

IllegalStateException: Realm instance can only be closed on the thread it was created.

What is wrong with this approach? 这种方法有什么问题? Can provide more info if needed. 如果需要,可以提供更多信息。

Probably because you're setting the class variable to another Realm, and you have some fairly intricate multi-threading problem going on; 可能是因为您将类变量设置为另一个Realm,并且您遇到了一些相当复杂的多线程问题。 nothing to do with device-specificness. 与设备特定性无关。

Solution: don't set the class level variable? 解决方案:不设置类级别变量?

public long getPendingImagesCount() {
    try(Realm realm = Realm.getInstance(RealmUtils.getRealmConfiguration())) {
        return realm.where(PatientRecordImage.class).count();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM