Skip to content

Instantly share code, notes, and snippets.

@SeongUgJung
Last active December 18, 2016 07:41
Show Gist options
  • Save SeongUgJung/390a3a572e1d08cce103abf81d78e9d2 to your computer and use it in GitHub Desktop.
Save SeongUgJung/390a3a572e1d08cce103abf81d78e9d2 to your computer and use it in GitHub Desktop.
public class DataRepository extends RealmRepository {
private static DataRepository instance;
synchronized public static DataRepository getInstance() {
if (instance == null) {
instance = new BotRepository();
}
return instance;
}
public Data getData(long memberId) {
return execute(realm -> {
Bot bot = realm.where(Data.class)
.equalTo("id", memberId)
.findFirst();
if (bot != null) {
return realm.copyFromRealm(bot);
} else {
return null;
}
});
}
}
public class RealmRepository {
private Lock lock;
protected RealmRepository() {lock = new ReentrantLock();}
protected <T> T execute(Executor<T> executor) {
Realm realm = null;
try {
lock.lock();
realm = Realm.getDefaultInstance();
return executor.execute(realm);
} finally {
if (realm != null && !realm.isClosed()) {
realm.close();
}
lock.unlock();
}
}
public interface Executor<T> {
T execute(Realm realm);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment