View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package org.jdbi.v3.cache.guava;
15  
16  import com.google.common.cache.CacheBuilder;
17  import org.jdbi.v3.core.cache.JdbiCache;
18  import org.jdbi.v3.core.cache.JdbiCacheBuilder;
19  import org.jdbi.v3.core.cache.JdbiCacheLoader;
20  
21  /**
22   * Cache builder using the guava {@link com.google.common.cache.Cache} object.
23   */
24  public final class GuavaCacheBuilder implements JdbiCacheBuilder {
25  
26      private final CacheBuilder<Object, Object> cacheBuilder;
27  
28      /**
29       * Returns a new {@link JdbiCacheBuilder} which can be used to construct the internal caches.
30       *
31       * @return A {@link JdbiCacheBuilder} instance.
32       */
33      public static JdbiCacheBuilder instance() {
34          return new GuavaCacheBuilder();
35      }
36  
37      /**
38       * Wraps an existing {@link CacheBuilder} for use with Jdbi.
39       *
40       * @param cacheBuilder A {@link CacheBuilder} instance.
41       */
42      public GuavaCacheBuilder(CacheBuilder<Object, Object> cacheBuilder) {
43          this.cacheBuilder = cacheBuilder;
44      }
45  
46      GuavaCacheBuilder() {
47          this.cacheBuilder = CacheBuilder.newBuilder().recordStats();
48      }
49  
50      @Override
51      public <K, V> JdbiCache<K, V> build() {
52          return new GuavaCache<>(cacheBuilder);
53      }
54  
55      @Override
56      public <K, V> JdbiCache<K, V> buildWithLoader(JdbiCacheLoader<K, V> cacheLoader) {
57          return new GuavaLoadingCache<>(cacheBuilder, cacheLoader);
58      }
59  
60      @Override
61      public JdbiCacheBuilder maxSize(int maxSize) {
62          cacheBuilder.maximumSize(maxSize);
63          return this;
64      }
65  }