Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Last active September 22, 2017 19:20
Show Gist options
  • Save Zhuinden/320b14d4e96f8aa5d45eb851552d3b8c to your computer and use it in GitHub Desktop.
Save Zhuinden/320b14d4e96f8aa5d45eb851552d3b8c to your computer and use it in GitHub Desktop.
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