1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.cache;
17
18 import static org.junit.jupiter.api.Assertions.assertNotNull;
19 import static org.junit.jupiter.api.Assertions.assertNull;
20 import static org.junit.jupiter.api.Assertions.assertTrue;
21
22 import org.apache.ibatis.cache.decorators.SerializedCache;
23 import org.apache.ibatis.cache.decorators.WeakCache;
24 import org.apache.ibatis.cache.impl.PerpetualCache;
25 import org.junit.jupiter.api.Test;
26
27 class WeakCacheTest {
28
29 @Test
30 void shouldDemonstrateObjectsBeingCollectedAsNeeded() {
31 final int N = 3000000;
32 WeakCache cache = new WeakCache(new PerpetualCache("default"));
33 for (int i = 0; i < N; i++) {
34 cache.putObject(i, i);
35 if (cache.getSize() < i + 1) {
36
37 break;
38 }
39 if ((i + 1) % 100000 == 0) {
40
41 System.gc();
42 }
43 }
44 assertTrue(cache.getSize() < N);
45 }
46
47 @Test
48 void shouldDemonstrateCopiesAreEqual() {
49 Cache cache = new WeakCache(new PerpetualCache("default"));
50 cache = new SerializedCache(cache);
51 for (int i = 0; i < 1000; i++) {
52 cache.putObject(i, i);
53 Object value = cache.getObject(i);
54 assertTrue(value == null || value.equals(i));
55 }
56 }
57
58 @Test
59 void shouldRemoveItemOnDemand() {
60 WeakCache cache = new WeakCache(new PerpetualCache("default"));
61 cache.putObject(0, 0);
62 assertNotNull(cache.getObject(0));
63 cache.removeObject(0);
64 assertNull(cache.getObject(0));
65 }
66
67 @Test
68 void shouldFlushAllItemsOnDemand() {
69 WeakCache cache = new WeakCache(new PerpetualCache("default"));
70 for (int i = 0; i < 5; i++) {
71 cache.putObject(i, i);
72 }
73 assertNotNull(cache.getObject(0));
74 assertNotNull(cache.getObject(4));
75 cache.clear();
76 assertNull(cache.getObject(0));
77 assertNull(cache.getObject(4));
78 }
79
80 }