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

beginTransaction don't execute inside Thread start

Open brunocerk opened this issue 7 years ago • 6 comments

Goal

I want to make a transaction inside a new Thread

Actual Results

Nothing happens, no errors, my code after realm.beginTransaction() simply don't get executed, no breakpoints or logs are hit

Steps & Code to Reproduce

new Thread(() -> {
            Log.d("REALM TRANSACTION ", "SAVING ");
            Ralm realm = Realm.getDefaultInstance();
            if (realm.isInTransaction()) {
//                realm.beginTransaction();
                realm.commitTransaction();
//                realm.close();
            }
            realm.beginTransaction(); // After this line, nothing gets executed | Breakpoint here Hits
            realm.insertOrUpdate(data.getMobileDevice()); // Break point here dont hit
            realm.insertOrUpdate(data.getCFCs());
            realm.insertOrUpdate(instructors);
            realm.insertOrUpdate(studentsInfos);
            realm.commitTransaction();
            runOnUiThread(() -> relativeLayout.setVisibility(View.INVISIBLE));
            new Handler().postDelayed(() -> startActivity(new Intent(LoginActivity.this, MainActivity.class)),200);
        }).start();

Version of Realm and tooling

Realm version(s): 5.8.0

Android Studio version: 3.3.1

Which Android version and device(s): 22

brunocerk avatar Feb 17 '19 21:02 brunocerk

I assume you have an open transaction elsewhere. realm.beginTransaction() is blocking across threads (and processes).

That transaction must commit before beginTransaction() can finish.

Zhuinden avatar Feb 18 '19 03:02 Zhuinden

But i do check if realm.isInTransaction() and i do a realm.commitTransaction() if true, just then i do another realm.beginTransaction(), its all in the code i posted

brunocerk avatar Feb 18 '19 05:02 brunocerk

isInTransaction checks the Realm on this thread, not globally I think.

Zhuinden avatar Feb 18 '19 10:02 Zhuinden

Yes, isInTransaction only considers the current thread, unfortunately. On the other hand, it wouldn't be super useful if it did consider other threads as they might have released their write transaction by the time this method returns.

cmelchior avatar Feb 18 '19 16:02 cmelchior

And yes, the behaviour you report is consistent with the hypothesis that another thread or process is currently in a write transaction.

cmelchior avatar Feb 18 '19 16:02 cmelchior

I assume the above answered your questions. If not feel free to re-open this issue. Closing.

cmelchior avatar Mar 22 '19 08:03 cmelchior