de.greenrobot.dao.query.AbstractQueryData Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of greendao-encryption Show documentation
Show all versions of greendao-encryption Show documentation
greenDAO is a light and fast ORM for Android
package de.greenrobot.dao.query;
import java.lang.ref.WeakReference;
import android.os.Process;
import android.util.SparseArray;
import de.greenrobot.dao.AbstractDao;
abstract class AbstractQueryData> {
final String sql;
final AbstractDao dao;
final String[] initialValues;
final SparseArray> queriesForThreads;
AbstractQueryData(AbstractDao dao, String sql, String[] initialValues) {
this.dao = dao;
this.sql = sql;
this.initialValues = initialValues;
queriesForThreads = new SparseArray>();
}
/** Just an optimized version, which performs faster if the current thread is already the query's owner thread. */
Q forCurrentThread(Q query) {
if (Thread.currentThread() == query.ownerThread) {
System.arraycopy(initialValues, 0, query.parameters, 0, initialValues.length);
return query;
} else {
return forCurrentThread();
}
}
Q forCurrentThread() {
int threadId = Process.myTid();
if (threadId == 0) {
// Workaround for Robolectric, always returns 0
long id = Thread.currentThread().getId();
if (id < 0 || id > Integer.MAX_VALUE) {
throw new RuntimeException("Cannot handle thread ID: " + id);
}
threadId = (int) id;
}
synchronized (queriesForThreads) {
WeakReference queryRef = queriesForThreads.get(threadId);
Q query = queryRef != null ? queryRef.get() : null;
if (query == null) {
gc();
query = createQuery();
queriesForThreads.put(threadId, new WeakReference(query));
} else {
System.arraycopy(initialValues, 0, query.parameters, 0, initialValues.length);
}
return query;
}
}
abstract protected Q createQuery();
void gc() {
synchronized (queriesForThreads) {
for (int i = queriesForThreads.size() - 1; i >= 0; i--) {
if (queriesForThreads.valueAt(i).get() == null) {
queriesForThreads.remove(queriesForThreads.keyAt(i));
}
}
}
}
}