Skip to content

Instantly share code, notes, and snippets.

@dmytrodanylyk
Last active March 6, 2018 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmytrodanylyk/c12414834413908dc079ac3fe6614585 to your computer and use it in GitHub Desktop.
Save dmytrodanylyk/c12414834413908dc079ac3fe6614585 to your computer and use it in GitHub Desktop.
Realm test
// Test 1
for (int i = 0; i < 10; i++) {
// spawn new thread which call queryNoTransaction()
}
void queryNoTransaction() {
try (Realm realm = Realm.getDefaultInstance()) {
long start = System.currentTimeMillis();
RealmResults<UserProfile> users = realm.where(UserProfile.class).findAll();
List<UserProfile> userCopy = realm.copyFromRealm(users);
long end = System.currentTimeMillis();
L.d("time: " + (end - start));
}
}
// output
// time: 4949
// time: 4986
// time: 5022
// time: 5040
// ...
// Test 2
for (int i = 0; i < 10; i++) {
// spawn new thread which call queryTransaction()
}
void queryTransaction() {
Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
long start = System.currentTimeMillis();
RealmResults<UserProfile> users = realm.where(UserProfile.class).findAll();
List<UserProfile> userCopy = realm.copyFromRealm(users);
long end = System.currentTimeMillis();
L.d("time: " + (end - start));
}
});
}
// output
// time: 46
// time: 85
// time: 61
// time: 49
// ...
@dmytrodanylyk
Copy link
Author

Conclusion: if multiple queries are trying to query realm without transaction realm will be locked, until all queries are completed, when last query is completed - realm will be released. To prevent this use transaction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment