-
-
Save memfis19/f7b1f7f0bf598ac252a1e038dc69299e to your computer and use it in GitHub Desktop.
Thread-local Realm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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