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 java.util.concurrent.locks.ReadWriteLock;
19
20 /**
21 * SPI for cache providers.
22 * <p>
23 * One instance of cache will be created for each namespace.
24 * <p>
25 * The cache implementation must have a constructor that receives the cache id as an String parameter.
26 * <p>
27 * MyBatis will pass the namespace as id to the constructor.
28 *
29 * <pre>
30 * public MyCache(final String id) {
31 * if (id == null) {
32 * throw new IllegalArgumentException("Cache instances require an ID");
33 * }
34 * this.id = id;
35 * initialize();
36 * }
37 * </pre>
38 *
39 * @author Clinton Begin
40 */
41
42 public interface Cache {
43
44 /**
45 * @return The identifier of this cache
46 */
47 String getId();
48
49 /**
50 * @param key
51 * Can be any object but usually it is a {@link CacheKey}
52 * @param value
53 * The result of a select.
54 */
55 void putObject(Object key, Object value);
56
57 /**
58 * @param key
59 * The key
60 * @return The object stored in the cache.
61 */
62 Object getObject(Object key);
63
64 /**
65 * As of 3.3.0 this method is only called during a rollback
66 * for any previous value that was missing in the cache.
67 * This lets any blocking cache to release the lock that
68 * may have previously put on the key.
69 * A blocking cache puts a lock when a value is null
70 * and releases it when the value is back again.
71 * This way other threads will wait for the value to be
72 * available instead of hitting the database.
73 *
74 *
75 * @param key
76 * The key
77 * @return Not used
78 */
79 Object removeObject(Object key);
80
81 /**
82 * Clears this cache instance.
83 */
84 void clear();
85
86 /**
87 * Optional. This method is not called by the core.
88 *
89 * @return The number of elements stored in the cache (not its capacity).
90 */
91 int getSize();
92
93 /**
94 * Optional. As of 3.2.6 this method is no longer called by the core.
95 * <p>
96 * Any locking needed by the cache must be provided internally by the cache provider.
97 *
98 * @return A ReadWriteLock
99 */
100 default ReadWriteLock getReadWriteLock() {
101 return null;
102 }
103
104 }