Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Thread-local Realm
@Singleton
public class RealmManager {
private ThreadLocal<Realm> realms;
@Inject
public RealmManager() {
realms = new ThreadLocal<>();
}
public Realm openRealm() {
Realm realm = realms.get();
if(realm != null && !realm.isClosed()) {
throw new IllegalStateException("Realm is already open");
}
realm = Realm.getDefaultInstance();
realms.set(realm);
return realm;
}
public Realm getRealm() {
Realm realm = realms.get();
if(realm == null) {
throw new IllegalStateException("There is no open Realm on this thread");
}
return realm;
}
public void closeRealm() {
Realm realm = realms.get();
if(realm == null) {
throw new IllegalStateException("No Realm found to close");
}
if(!realm.isClosed()) {
realm.close();
}
realms.set(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.