Skip to content

Commit f6e435e

Browse files
Query clone: add a QueryThreadLocal and test (#34)
1 parent 4262c5d commit f6e435e

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package io.objectbox.query;
2+
3+
/**
4+
* A {@link ThreadLocal} that, given an original {@link Query} object,
5+
* returns a {@link Query#copy() copy}, for each thread.
6+
*/
7+
public class QueryThreadLocal<T> extends ThreadLocal<Query<T>> {
8+
9+
private final Query<T> original;
10+
11+
/**
12+
* See {@link QueryThreadLocal}.
13+
*/
14+
public QueryThreadLocal(Query<T> original) {
15+
this.original = original;
16+
}
17+
18+
@Override
19+
protected Query<T> initialValue() {
20+
return original.copy();
21+
}
22+
}

tests/objectbox-java-test/src/test/java/io/objectbox/query/QueryCopyTest.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
import java.util.Comparator;
88
import java.util.List;
9+
import java.util.concurrent.CountDownLatch;
10+
import java.util.concurrent.TimeUnit;
11+
import java.util.concurrent.atomic.AtomicReference;
912

1013
import static org.junit.Assert.*;
1114

@@ -79,4 +82,35 @@ private void assertTestEntityEquals(TestEntity expected, TestEntity actual) {
7982
assertEquals(expected.getId(), actual.getId());
8083
assertEquals(expected.getSimpleString(), actual.getSimpleString());
8184
}
85+
86+
@Test
87+
public void queryThreadLocal() throws InterruptedException {
88+
Query<TestEntity> queryOriginal = box.query().build();
89+
QueryThreadLocal<TestEntity> threadLocal = new QueryThreadLocal<>(queryOriginal);
90+
91+
AtomicReference<Query<TestEntity>> queryThreadAtomic = new AtomicReference<>();
92+
CountDownLatch latch = new CountDownLatch(1);
93+
new Thread(() -> {
94+
queryThreadAtomic.set(threadLocal.get());
95+
latch.countDown();
96+
}).start();
97+
98+
assertTrue(latch.await(1, TimeUnit.SECONDS));
99+
100+
Query<TestEntity> queryThread = queryThreadAtomic.get();
101+
Query<TestEntity> queryMain = threadLocal.get();
102+
103+
// Assert that initialValue returns something.
104+
assertNotNull(queryThread);
105+
assertNotNull(queryMain);
106+
107+
// Assert that initialValue returns clones.
108+
assertNotEquals(queryThread.handle, queryOriginal.handle);
109+
assertNotEquals(queryMain.handle, queryOriginal.handle);
110+
assertNotEquals(queryThread.handle, queryMain.handle);
111+
112+
queryOriginal.close();
113+
queryMain.close();
114+
queryThread.close();
115+
}
82116
}

0 commit comments

Comments
 (0)