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.assertEquals;
19  import static org.junit.jupiter.api.Assertions.assertNotNull;
20  import static org.junit.jupiter.api.Assertions.assertNull;
21  
22  import org.apache.ibatis.cache.decorators.LoggingCache;
23  import org.apache.ibatis.cache.decorators.ScheduledCache;
24  import org.apache.ibatis.cache.impl.PerpetualCache;
25  import org.junit.jupiter.api.Test;
26  
27  class ScheduledCacheTest {
28  
29    @Test
30    void shouldDemonstrateHowAllObjectsAreFlushedAfterBasedOnTime() throws Exception {
31      Cache cache = new PerpetualCache("DefaultCache");
32      cache = new ScheduledCache(cache);
33      ((ScheduledCache) cache).setClearInterval(2500);
34      cache = new LoggingCache(cache);
35      for (int i = 0; i < 100; i++) {
36        cache.putObject(i, i);
37        assertEquals(i, cache.getObject(i));
38      }
39      Thread.sleep(5000);
40      assertEquals(0, cache.getSize());
41    }
42  
43    @Test
44    void shouldRemoveItemOnDemand() {
45      Cache cache = new PerpetualCache("DefaultCache");
46      cache = new ScheduledCache(cache);
47      ((ScheduledCache) cache).setClearInterval(60000);
48      cache = new LoggingCache(cache);
49      cache.putObject(0, 0);
50      assertNotNull(cache.getObject(0));
51      cache.removeObject(0);
52      assertNull(cache.getObject(0));
53    }
54  
55    @Test
56    void shouldFlushAllItemsOnDemand() {
57      Cache cache = new PerpetualCache("DefaultCache");
58      cache = new ScheduledCache(cache);
59      ((ScheduledCache) cache).setClearInterval(60000);
60      cache = new LoggingCache(cache);
61      for (int i = 0; i < 5; i++) {
62        cache.putObject(i, i);
63      }
64      assertNotNull(cache.getObject(0));
65      assertNotNull(cache.getObject(4));
66      cache.clear();
67      assertNull(cache.getObject(0));
68      assertNull(cache.getObject(4));
69    }
70  
71  }