View Javadoc
1   /*
2    *    Copyright 2009-2022 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
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          // System.out.println("Cache exceeded with " + (i + 1) + " entries.");
37          break;
38        }
39        if ((i + 1) % 100000 == 0) {
40          // Try performing GC.
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  }