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