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