View Javadoc
1   /*
2    *    Copyright 2009-2023 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.SoftCache;
24  import org.apache.ibatis.cache.impl.PerpetualCache;
25  import org.junit.jupiter.api.Test;
26  
27  class SoftCacheTest {
28  
29    @Test
30    void shouldDemonstrateObjectsBeingCollectedAsNeeded() {
31      final int N = 3000000;
32      SoftCache cache = new SoftCache(new PerpetualCache("default"));
33      for (int i = 0; i < N; i++) {
34        byte[] array = new byte[5001]; // waste a bunch of memory
35        array[5000] = 1;
36        cache.putObject(i, array);
37        cache.getObject(i);
38        if (cache.getSize() < i + 1) {
39          // System.out.println("Cache exceeded with " + (i + 1) + " entries.");
40          break;
41        }
42      }
43      assertTrue(cache.getSize() < N);
44    }
45  
46    @Test
47    void shouldDemonstrateCopiesAreEqual() {
48      Cache cache = new SoftCache(new PerpetualCache("default"));
49      cache = new SerializedCache(cache);
50      for (int i = 0; i < 1000; i++) {
51        cache.putObject(i, i);
52        Object value = cache.getObject(i);
53        assertTrue(value == null || value.equals(i));
54      }
55    }
56  
57    @Test
58    void shouldRemoveItemOnDemand() {
59      Cache cache = new SoftCache(new PerpetualCache("default"));
60      cache.putObject(0, 0);
61      assertNotNull(cache.getObject(0));
62      cache.removeObject(0);
63      assertNull(cache.getObject(0));
64    }
65  
66    @Test
67    void shouldFlushAllItemsOnDemand() {
68      Cache cache = new SoftCache(new PerpetualCache("default"));
69      for (int i = 0; i < 5; i++) {
70        cache.putObject(i, i);
71      }
72      assertNotNull(cache.getObject(0));
73      assertNotNull(cache.getObject(4));
74      cache.clear();
75      assertNull(cache.getObject(0));
76      assertNull(cache.getObject(4));
77    }
78  
79  }