realm-java icon indicating copy to clipboard operation
realm-java copied to clipboard

Cannot create asynchronous query while in a write transaction in /Users/Nabil/Dev/realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_Collection.cpp line 274

Open preyesm opened this issue 8 years ago • 26 comments

Hi, I keep getting this crash and has affected significant number of users. Usecase:

  1. Profile page which fetches data from two different asynchronous apis.
  2. The above crash is at changeListener for the object for results of 2nd API.

Wanted to confirm, if there is data write going on in realm in a execute transaction block, will this crash happen at the change listener of the other objects. I was under the perception that execute transaction block is in itself a seperate thread and ideally asynchronous query error should not be thrown. Can you correct me on what is the core reason of this issue. Thanks

preyesm avatar Feb 27 '18 06:02 preyesm

This crash happens if you run an asynchronous query inside a write transaction. It is not related to the change listener as such.

// Async query
realm.beginTransaction();
RealmResults<Person> people = realm.where(Person.class).findAllAsync(); // Will throw
realm.commitTransaction();

// Use sync query instead
realm.beginTransaction();
RealmResults<Person> people = realm.where(Person.class).findAll(); // Will not throw
realm.commitTransaction();

This restriction is in place because when triggering notification listeners, we need to have a stable version to calculate changes from, and inside a write transaction, you are in the middle of changing values.

cmelchior avatar Feb 27 '18 10:02 cmelchior

But @cmelchior, i have not used any async transaction in my application and also all crashes in this category occur only at page where there are more than one change listener and crash report points to the change listener LOC.

preyesm avatar Feb 27 '18 10:02 preyesm

async query like findAllAsync

I cannot really tell you anything without code, especially if Rx is involved.

Zhuinden avatar Feb 27 '18 11:02 Zhuinden

There is no Rx involved. I can share the bit pieces of code of my transaction write, but I doubt if it will provide any info.

preyesm avatar Feb 27 '18 12:02 preyesm

Well anything to do with transactions in change listeners is a good bet 😄

Zhuinden avatar Feb 27 '18 13:02 Zhuinden

Sure. Terminating app due to an uncaught exception 'java.lang.IllegalStateException', reason: 'Cannot create asynchronous query while in a write transaction in /Users/Nabil/Dev/realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_Collection.cpp line 274' Transaction update code for requests in same page: Realm realm = Realm.getDefaultInstance(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { System.out.println("realm Group Members updated"); realm.where(GroupMember.class).equalTo("groupId", groupId).findAll().deleteAllFromRealm(); Iterator iterator = response.connections.iterator(); while (iterator.hasNext()) { AgentProfileCache agentProfileCache = iterator.next(); realm.insertOrUpdate(new GroupMember(agentProfileCache.getId(), groupId)); if (agentProfileCache.getId().equals(ApplicationDataHandler.getMyAgentId())) { iterator.remove(); } else { realm.insertOrUpdate(agentProfileCache); } } } } } realm.close();

Another tansaction udpate code: ApplicationDataHandler.getRealm().executeTransaction(realm -> { realm.insertOrUpdate(networkGroupCache); });

the crash happens at : groupMembers.addChangeListener(element -> { loadMemberImages(); });

All realm transaction in the app are sync but coz this data is huge i have put this under async execute.

preyesm avatar Feb 28 '18 05:02 preyesm

What is loadMemberImages();?

Also, add ``` around your code so that it is formatted.

Zhuinden avatar Feb 28 '18 09:02 Zhuinden

it is a function which displays the thumbnail images of the members of the group.

preyesm avatar Feb 28 '18 09:02 preyesm

okay, so the formatted code is


        Realm realm = Realm.getDefaultInstance();
        realm.executeTransactionAsync(new Realm.Transaction() {
            @override
            public void execute(Realm realm) {
                System.out.println("realm Group Members updated");
                realm.where(GroupMember.class).equalTo("groupId", groupId).findAll().deleteAllFromRealm();
                Iterator iterator = response.connections.iterator();
                while (iterator.hasNext()) {
                    AgentProfileCache agentProfileCache = iterator.next();
                    realm.insertOrUpdate(new GroupMember(agentProfileCache.getId(), groupId));
                    if (agentProfileCache.getId().equals(ApplicationDataHandler.getMyAgentId())) {
                        iterator.remove();
                    } else {
                        realm.insertOrUpdate(agentProfileCache);
                    }
                }
            }
        }
    }
    realm.close();

But where exactly is

groupMembers.addChangeListener(element -> {
   loadMemberImages();
});

?

Zhuinden avatar Feb 28 '18 10:02 Zhuinden

That is in the view of my app. the realm update code is in the data model whereas the change listener is in the view part and the load Member image function does only one job -> display image,

preyesm avatar Feb 28 '18 10:02 preyesm

Like, code context.

Zhuinden avatar Feb 28 '18 10:02 Zhuinden

did not get you. this is the loadMemberImage function for (String key : urls.keySet()) { LayoutOnlyImageBinding imageBinding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.layout_only_image, binding.memberImageLayout, false); CollectionUtils.setAgentAvatar(urls.get(key), imageBinding.image, key, 5); binding.memberImageLayout.addView(imageBinding.getRoot()); }

preyesm avatar Feb 28 '18 11:02 preyesm

How to solve this problem? I also encountered the same error, I am using rxjava.

bbbBBBSG avatar Oct 11 '18 09:10 bbbBBBSG

Don't call findAllAsync inside a write transaction.

Zhuinden avatar Oct 11 '18 09:10 Zhuinden

I will delete the inserted code or will report an error. The situation is like this, when the activity is killed in the background, then enter the activity add addChangeListener is reported error.
Code

private RealmResults<ScreenAd> mScreenAds;
// run on onCreate:
        mScreenAds = getUserRealm().where(ScreenAd.class)
                .greaterThan("endTime", System.currentTimeMillis())
                .equalTo("canShow", true)
                .isNotEmpty("adImageUrl")
                .findAllSorted("timestamp", Sort.ASCENDING);
// run on onStart:
       if (mScreenAds != null) {
            mScreenAds.addChangeListener(new RealmChangeListener<RealmResults<ScreenAd>>() {
                @Override
                public void onChange(RealmResults<ScreenAd> screenAds) {
                    showScreenAd();
                }
            });
        }

bbbBBBSG avatar Oct 11 '18 10:10 bbbBBBSG

Add error log

     Caused by: java.lang.IllegalStateException: Cannot create asynchronous query while in a write transaction in /home/cc/repo/realm/release/realm/realm-library/src/main/cpp/io_realm_internal_Collection.cpp line 329
        at io.realm.internal.Collection.nativeStartListening(Native Method)
        at io.realm.internal.Collection.addListener(Collection.java:486)
        at io.realm.internal.Collection.addListener(Collection.java:493)
        at io.realm.RealmResults.addChangeListener(RealmResults.java:175)

bbbBBBSG avatar Oct 11 '18 10:10 bbbBBBSG

We currently have a limitation that means you cannot add listeners inside a write transaction due to the way listeners work, it looks like you are running into that here.

cmelchior avatar Oct 11 '18 10:10 cmelchior

We currently have a limitation that means you cannot add listeners inside a write transaction due to the way listeners work, it looks like you are running into that here.

I have no transaction now. Still report an error, please see https://github.com/realm/realm-java/issues/5771#issuecomment-428901359

bbbBBBSG avatar Oct 11 '18 10:10 bbbBBBSG

Are you 100% sure that there is no transaction open there?

Zhuinden avatar Oct 11 '18 13:10 Zhuinden

I read the document, and I also judged whether there was a transaction in execution, and there was no mistake in making the judgement. Realm.isInTransaction

If the write transaction happened on the same thread, the listener will be called synchronously when the transaction is committed. However, in some cases the listener may be called when the transaction starts—if the Realm is advanced to the latest version, or Realm entities being observed were modified or deleted in a way that triggers notifications. In those cases, the listener runs within the context of the current write transaction, so an attempt to begin a new write transaction within the notification handler will throw an exception. You can use the Realm.isInTransaction method to determine if your code is executing within a write transaction.

Thanks very much!!!

bbbBBBSG avatar Oct 12 '18 02:10 bbbBBBSG