001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.cache;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.base.Ascii;
024import com.google.common.base.Equivalence;
025import com.google.common.base.MoreObjects;
026import com.google.common.base.Supplier;
027import com.google.common.base.Suppliers;
028import com.google.common.base.Ticker;
029import com.google.common.cache.AbstractCache.SimpleStatsCounter;
030import com.google.common.cache.AbstractCache.StatsCounter;
031import com.google.common.cache.LocalCache.Strength;
032import com.google.errorprone.annotations.CheckReturnValue;
033import java.lang.ref.SoftReference;
034import java.lang.ref.WeakReference;
035import java.util.ConcurrentModificationException;
036import java.util.IdentityHashMap;
037import java.util.Map;
038import java.util.concurrent.ConcurrentHashMap;
039import java.util.concurrent.TimeUnit;
040import java.util.logging.Level;
041import java.util.logging.Logger;
042import org.checkerframework.checker.nullness.qual.Nullable;
043
044/**
045 * A builder of {@link LoadingCache} and {@link Cache} instances.
046 *
047 * <h2>Prefer <a href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a> over Guava's caching
048 * API</h2>
049 *
050 * <p>The successor to Guava's caching API is <a
051 * href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>. Its API is designed to make it a
052 * nearly drop-in replacement -- though it requires Java 8 APIs, is not available for Android or
053 * GWT/j2cl, and may have <a href="https://github.com/ben-manes/caffeine/wiki/Guava">different
054 * (usually better) behavior</a> when multiple threads attempt concurrent mutations. Its equivalent
055 * to {@code CacheBuilder} is its <a
056 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html">{@code
057 * Caffeine}</a> class. Caffeine offers better performance, more features (including asynchronous
058 * loading), and fewer <a
059 * href="https://github.com/google/guava/issues?q=is%3Aopen+is%3Aissue+label%3Apackage%3Dcache+label%3Atype%3Ddefect">bugs</a>.
060 *
061 * <p>Caffeine defines its own interfaces (<a
062 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Cache.html">{@code
063 * Cache}</a>, <a
064 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/LoadingCache.html">{@code
065 * LoadingCache}</a>, <a
066 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/CacheLoader.html">{@code
067 * CacheLoader}</a>, etc.), so you can use Caffeine without needing to use any Guava types.
068 * Caffeine's types are better than Guava's, especially for <a
069 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html">their
070 * deep support for asynchronous operations</a>. But if you want to migrate to Caffeine with minimal
071 * code changes, you can use <a
072 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/guava/latest/com.github.benmanes.caffeine.guava/com/github/benmanes/caffeine/guava/CaffeinatedGuava.html">its
073 * {@code CaffeinatedGuava} adapter class</a>, which lets you build a Guava {@code Cache} or a Guava
074 * {@code LoadingCache} backed by a Guava {@code CacheLoader}.
075 *
076 * <p>Caffeine's API for asynchronous operations uses {@code CompletableFuture}: <a
077 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html#get(K)">{@code
078 * AsyncLoadingCache.get}</a> returns a {@code CompletableFuture}, and implementations of <a
079 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncCacheLoader.html#asyncLoad(K,java.util.concurrent.Executor)">{@code
080 * AsyncCacheLoader.asyncLoad}</a> must return a {@code CompletableFuture}. Users of Guava's {@link
081 * com.google.common.util.concurrent.ListenableFuture} can adapt between the two {@code Future}
082 * types by using <a href="https://github.com/lukas-krecan/future-converter#java8-guava">{@code
083 * net.javacrumbs.futureconverter.java8guava.FutureConverter}</a>.
084 *
085 * <h2>More on {@code CacheBuilder}</h2>
086 *
087 * {@code CacheBuilder} builds caches with any combination of the following features:
088 *
089 * <ul>
090 *   <li>automatic loading of entries into the cache
091 *   <li>least-recently-used eviction when a maximum size is exceeded (note that the cache is
092 *       divided into segments, each of which does LRU internally)
093 *   <li>time-based expiration of entries, measured since last access or last write
094 *   <li>keys automatically wrapped in {@code WeakReference}
095 *   <li>values automatically wrapped in {@code WeakReference} or {@code SoftReference}
096 *   <li>notification of evicted (or otherwise removed) entries
097 *   <li>accumulation of cache access statistics
098 * </ul>
099 *
100 * <p>These features are all optional; caches can be created using all or none of them. By default
101 * cache instances created by {@code CacheBuilder} will not perform any type of eviction.
102 *
103 * <p>Usage example:
104 *
105 * <pre>{@code
106 * LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
107 *     .maximumSize(10000)
108 *     .expireAfterWrite(10, TimeUnit.MINUTES)
109 *     .removalListener(MY_LISTENER)
110 *     .build(
111 *         new CacheLoader<Key, Graph>() {
112 *           public Graph load(Key key) throws AnyException {
113 *             return createExpensiveGraph(key);
114 *           }
115 *         });
116 * }</pre>
117 *
118 * <p>Or equivalently,
119 *
120 * <pre>{@code
121 * // In real life this would come from a command-line flag or config file
122 * String spec = "maximumSize=10000,expireAfterWrite=10m";
123 *
124 * LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
125 *     .removalListener(MY_LISTENER)
126 *     .build(
127 *         new CacheLoader<Key, Graph>() {
128 *           public Graph load(Key key) throws AnyException {
129 *             return createExpensiveGraph(key);
130 *           }
131 *         });
132 * }</pre>
133 *
134 * <p>The returned cache is implemented as a hash table with similar performance characteristics to
135 * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
136 * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
137 * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
138 * modify the cache after the iterator is created, it is undefined which of these changes, if any,
139 * are reflected in that iterator. These iterators never throw {@link
140 * ConcurrentModificationException}.
141 *
142 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link
143 * Object#equals equals} method) to determine equality for keys or values. However, if {@link
144 * #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for keys.
145 * Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity
146 * comparisons for values.
147 *
148 * <p>Entries are automatically evicted from the cache when any of {@linkplain #maximumSize(long)
149 * maximumSize}, {@linkplain #maximumWeight(long) maximumWeight}, {@linkplain #expireAfterWrite
150 * expireAfterWrite}, {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys
151 * weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are
152 * requested.
153 *
154 * <p>If {@linkplain #maximumSize(long) maximumSize} or {@linkplain #maximumWeight(long)
155 * maximumWeight} is requested entries may be evicted on each cache modification.
156 *
157 * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or {@linkplain #expireAfterAccess
158 * expireAfterAccess} is requested entries may be evicted on each cache modification, on occasional
159 * cache accesses, or on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link
160 * Cache#size}, but will never be visible to read or write operations.
161 *
162 * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain
163 * #softValues softValues} are requested, it is possible for a key or value present in the cache to
164 * be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from
165 * the cache on each cache modification, on occasional cache accesses, or on calls to {@link
166 * Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be visible to
167 * read or write operations.
168 *
169 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
170 * will be performed during write operations, or during occasional read operations in the absence of
171 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
172 * calling it should not be necessary with a high throughput cache. Only caches built with
173 * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
174 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys}, {@linkplain
175 * #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic maintenance.
176 *
177 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
178 * retain all the configuration properties of the original cache. Note that the serialized form does
179 * <i>not</i> include cache contents, but only configuration.
180 *
181 * <p>See the Guava User Guide article on <a
182 * href="https://github.com/google/guava/wiki/CachesExplained">caching</a> for a higher-level
183 * explanation.
184 *
185 * @param <K> the most general key type this builder will be able to create caches for. This is
186 *     normally {@code Object} unless it is constrained by using a method like {@code
187 *     #removalListener}. Cache keys may not be null.
188 * @param <V> the most general value type this builder will be able to create caches for. This is
189 *     normally {@code Object} unless it is constrained by using a method like {@code
190 *     #removalListener}. Cache values may not be null.
191 * @author Charles Fry
192 * @author Kevin Bourrillion
193 * @since 10.0
194 */
195@GwtCompatible(emulated = true)
196@ElementTypesAreNonnullByDefault
197public final class CacheBuilder<K, V> {
198  private static final int DEFAULT_INITIAL_CAPACITY = 16;
199  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
200
201  @SuppressWarnings("GoodTime") // should be a java.time.Duration
202  private static final int DEFAULT_EXPIRATION_NANOS = 0;
203
204  @SuppressWarnings("GoodTime") // should be a java.time.Duration
205  private static final int DEFAULT_REFRESH_NANOS = 0;
206
207  static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER =
208      Suppliers.ofInstance(
209          new StatsCounter() {
210            @Override
211            public void recordHits(int count) {}
212
213            @Override
214            public void recordMisses(int count) {}
215
216            @SuppressWarnings("GoodTime") // b/122668874
217            @Override
218            public void recordLoadSuccess(long loadTime) {}
219
220            @SuppressWarnings("GoodTime") // b/122668874
221            @Override
222            public void recordLoadException(long loadTime) {}
223
224            @Override
225            public void recordEviction() {}
226
227            @Override
228            public CacheStats snapshot() {
229              return EMPTY_STATS;
230            }
231          });
232  static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
233
234  static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
235      new Supplier<StatsCounter>() {
236        @Override
237        public StatsCounter get() {
238          return new SimpleStatsCounter();
239        }
240      };
241
242  enum NullListener implements RemovalListener<Object, Object> {
243    INSTANCE;
244
245    @Override
246    public void onRemoval(RemovalNotification<Object, Object> notification) {}
247  }
248
249  enum OneWeigher implements Weigher<Object, Object> {
250    INSTANCE;
251
252    @Override
253    public int weigh(Object key, Object value) {
254      return 1;
255    }
256  }
257
258  static final Ticker NULL_TICKER =
259      new Ticker() {
260        @Override
261        public long read() {
262          return 0;
263        }
264      };
265
266  private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
267
268  static final int UNSET_INT = -1;
269
270  boolean strictParsing = true;
271
272  int initialCapacity = UNSET_INT;
273  int concurrencyLevel = UNSET_INT;
274  long maximumSize = UNSET_INT;
275  long maximumWeight = UNSET_INT;
276  @Nullable Weigher<? super K, ? super V> weigher;
277
278  @Nullable Strength keyStrength;
279  @Nullable Strength valueStrength;
280
281  @SuppressWarnings("GoodTime") // should be a java.time.Duration
282  long expireAfterWriteNanos = UNSET_INT;
283
284  @SuppressWarnings("GoodTime") // should be a java.time.Duration
285  long expireAfterAccessNanos = UNSET_INT;
286
287  @SuppressWarnings("GoodTime") // should be a java.time.Duration
288  long refreshNanos = UNSET_INT;
289
290  @Nullable Equivalence<Object> keyEquivalence;
291  @Nullable Equivalence<Object> valueEquivalence;
292
293  @Nullable RemovalListener<? super K, ? super V> removalListener;
294  @Nullable Ticker ticker;
295
296  Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
297
298  private CacheBuilder() {}
299
300  /**
301   * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
302   * strong values, and no automatic eviction of any kind.
303   *
304   * <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on
305   * the {@link #build} methods allow you to create a cache of any key and value type desired.
306   */
307  @CheckReturnValue
308  public static CacheBuilder<Object, Object> newBuilder() {
309    return new CacheBuilder<>();
310  }
311
312  /**
313   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
314   *
315   * @since 12.0
316   */
317  @GwtIncompatible // To be supported
318  @CheckReturnValue
319  public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
320    return spec.toCacheBuilder().lenientParsing();
321  }
322
323  /**
324   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
325   * This is especially useful for command-line configuration of a {@code CacheBuilder}.
326   *
327   * @param spec a String in the format specified by {@link CacheBuilderSpec}
328   * @since 12.0
329   */
330  @GwtIncompatible // To be supported
331  @CheckReturnValue
332  public static CacheBuilder<Object, Object> from(String spec) {
333    return from(CacheBuilderSpec.parse(spec));
334  }
335
336  /**
337   * Enables lenient parsing. Useful for tests and spec parsing.
338   *
339   * @return this {@code CacheBuilder} instance (for chaining)
340   */
341  @GwtIncompatible // To be supported
342  CacheBuilder<K, V> lenientParsing() {
343    strictParsing = false;
344    return this;
345  }
346
347  /**
348   * Sets a custom {@code Equivalence} strategy for comparing keys.
349   *
350   * <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
351   * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
352   *
353   * @return this {@code CacheBuilder} instance (for chaining)
354   */
355  @GwtIncompatible // To be supported
356  CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
357    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
358    keyEquivalence = checkNotNull(equivalence);
359    return this;
360  }
361
362  Equivalence<Object> getKeyEquivalence() {
363    return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
364  }
365
366  /**
367   * Sets a custom {@code Equivalence} strategy for comparing values.
368   *
369   * <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
370   * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()}
371   * otherwise.
372   *
373   * @return this {@code CacheBuilder} instance (for chaining)
374   */
375  @GwtIncompatible // To be supported
376  CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
377    checkState(
378        valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
379    this.valueEquivalence = checkNotNull(equivalence);
380    return this;
381  }
382
383  Equivalence<Object> getValueEquivalence() {
384    return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
385  }
386
387  /**
388   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
389   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
390   * having a hash table of size eight. Providing a large enough estimate at construction time
391   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
392   * high wastes memory.
393   *
394   * @return this {@code CacheBuilder} instance (for chaining)
395   * @throws IllegalArgumentException if {@code initialCapacity} is negative
396   * @throws IllegalStateException if an initial capacity was already set
397   */
398  public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
399    checkState(
400        this.initialCapacity == UNSET_INT,
401        "initial capacity was already set to %s",
402        this.initialCapacity);
403    checkArgument(initialCapacity >= 0);
404    this.initialCapacity = initialCapacity;
405    return this;
406  }
407
408  int getInitialCapacity() {
409    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
410  }
411
412  /**
413   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
414   * table is internally partitioned to try to permit the indicated number of concurrent updates
415   * without contention. Because assignment of entries to these partitions is not necessarily
416   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
417   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
418   * higher value than you need can waste space and time, and a significantly lower value can lead
419   * to thread contention. But overestimates and underestimates within an order of magnitude do not
420   * usually have much noticeable impact. A value of one permits only one thread to modify the cache
421   * at a time, but since read operations and cache loading computations can proceed concurrently,
422   * this still yields higher concurrency than full synchronization.
423   *
424   * <p>Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
425   * value, you should always choose it explicitly.
426   *
427   * <p>The current implementation uses the concurrency level to create a fixed number of hashtable
428   * segments, each governed by its own write lock. The segment lock is taken once for each explicit
429   * write, and twice for each cache loading computation (once prior to loading the new value, and
430   * once after loading completes). Much internal cache management is performed at the segment
431   * granularity. For example, access queues and write queues are kept per segment when they are
432   * required by the selected eviction algorithm. As such, when writing unit tests it is not
433   * uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
434   * behavior.
435   *
436   * <p>Note that future implementations may abandon segment locking in favor of more advanced
437   * concurrency controls.
438   *
439   * @return this {@code CacheBuilder} instance (for chaining)
440   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
441   * @throws IllegalStateException if a concurrency level was already set
442   */
443  public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
444    checkState(
445        this.concurrencyLevel == UNSET_INT,
446        "concurrency level was already set to %s",
447        this.concurrencyLevel);
448    checkArgument(concurrencyLevel > 0);
449    this.concurrencyLevel = concurrencyLevel;
450    return this;
451  }
452
453  int getConcurrencyLevel() {
454    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
455  }
456
457  /**
458   * Specifies the maximum number of entries the cache may contain.
459   *
460   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
461   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
462   * resulting segment inside the cache <i>independently</i> limits its own size to approximately
463   * {@code maximumSize / concurrencyLevel}.
464   *
465   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
466   * For example, the cache may evict an entry because it hasn't been used recently or very often.
467   *
468   * <p>If {@code maximumSize} is zero, elements will be evicted immediately after being loaded into
469   * cache. This can be useful in testing, or to disable caching temporarily.
470   *
471   * <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
472   *
473   * @param maximumSize the maximum size of the cache
474   * @return this {@code CacheBuilder} instance (for chaining)
475   * @throws IllegalArgumentException if {@code maximumSize} is negative
476   * @throws IllegalStateException if a maximum size or weight was already set
477   */
478  public CacheBuilder<K, V> maximumSize(long maximumSize) {
479    checkState(
480        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
481    checkState(
482        this.maximumWeight == UNSET_INT,
483        "maximum weight was already set to %s",
484        this.maximumWeight);
485    checkState(this.weigher == null, "maximum size can not be combined with weigher");
486    checkArgument(maximumSize >= 0, "maximum size must not be negative");
487    this.maximumSize = maximumSize;
488    return this;
489  }
490
491  /**
492   * Specifies the maximum weight of entries the cache may contain. Weight is determined using the
493   * {@link Weigher} specified with {@link #weigher}, and use of this method requires a
494   * corresponding call to {@link #weigher} prior to calling {@link #build}.
495   *
496   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
497   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
498   * resulting segment inside the cache <i>independently</i> limits its own weight to approximately
499   * {@code maximumWeight / concurrencyLevel}.
500   *
501   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
502   * For example, the cache may evict an entry because it hasn't been used recently or very often.
503   *
504   * <p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded
505   * into cache. This can be useful in testing, or to disable caching temporarily.
506   *
507   * <p>Note that weight is only used to determine whether the cache is over capacity; it has no
508   * effect on selecting which entry should be evicted next.
509   *
510   * <p>This feature cannot be used in conjunction with {@link #maximumSize}.
511   *
512   * @param maximumWeight the maximum total weight of entries the cache may contain
513   * @return this {@code CacheBuilder} instance (for chaining)
514   * @throws IllegalArgumentException if {@code maximumWeight} is negative
515   * @throws IllegalStateException if a maximum weight or size was already set
516   * @since 11.0
517   */
518  @GwtIncompatible // To be supported
519  public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
520    checkState(
521        this.maximumWeight == UNSET_INT,
522        "maximum weight was already set to %s",
523        this.maximumWeight);
524    checkState(
525        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
526    checkArgument(maximumWeight >= 0, "maximum weight must not be negative");
527    this.maximumWeight = maximumWeight;
528    return this;
529  }
530
531  /**
532   * Specifies the weigher to use in determining the weight of entries. Entry weight is taken into
533   * consideration by {@link #maximumWeight(long)} when determining which entries to evict, and use
534   * of this method requires a corresponding call to {@link #maximumWeight(long)} prior to calling
535   * {@link #build}. Weights are measured and recorded when entries are inserted into the cache, and
536   * are thus effectively static during the lifetime of a cache entry.
537   *
538   * <p>When the weight of an entry is zero it will not be considered for size-based eviction
539   * (though it still may be evicted by other means).
540   *
541   * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
542   * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
543   * original reference or the returned reference may be used to complete configuration and build
544   * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
545   * building caches whose key or value types are incompatible with the types accepted by the
546   * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
547   * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
548   * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
549   *
550   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build a
551   * cache whose key or value type is incompatible with the weigher, you will likely experience a
552   * {@link ClassCastException} at some <i>undefined</i> point in the future.
553   *
554   * @param weigher the weigher to use in calculating the weight of cache entries
555   * @return this {@code CacheBuilder} instance (for chaining)
556   * @throws IllegalArgumentException if {@code size} is negative
557   * @throws IllegalStateException if a maximum size was already set
558   * @since 11.0
559   */
560  @GwtIncompatible // To be supported
561  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
562      Weigher<? super K1, ? super V1> weigher) {
563    checkState(this.weigher == null);
564    if (strictParsing) {
565      checkState(
566          this.maximumSize == UNSET_INT,
567          "weigher can not be combined with maximum size",
568          this.maximumSize);
569    }
570
571    // safely limiting the kinds of caches this can produce
572    @SuppressWarnings("unchecked")
573    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
574    me.weigher = checkNotNull(weigher);
575    return me;
576  }
577
578  long getMaximumWeight() {
579    if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
580      return 0;
581    }
582    return (weigher == null) ? maximumSize : maximumWeight;
583  }
584
585  // Make a safe contravariant cast now so we don't have to do it over and over.
586  @SuppressWarnings("unchecked")
587  <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
588    return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
589  }
590
591  /**
592   * Specifies that each key (not value) stored in the cache should be wrapped in a {@link
593   * WeakReference} (by default, strong references are used).
594   *
595   * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
596   * comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore
597   * technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap}
598   * does).
599   *
600   * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size}, but
601   * will never be visible to read or write operations; such entries are cleaned up as part of the
602   * routine maintenance described in the class javadoc.
603   *
604   * @return this {@code CacheBuilder} instance (for chaining)
605   * @throws IllegalStateException if the key strength was already set
606   */
607  @GwtIncompatible // java.lang.ref.WeakReference
608  public CacheBuilder<K, V> weakKeys() {
609    return setKeyStrength(Strength.WEAK);
610  }
611
612  CacheBuilder<K, V> setKeyStrength(Strength strength) {
613    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
614    keyStrength = checkNotNull(strength);
615    return this;
616  }
617
618  Strength getKeyStrength() {
619    return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
620  }
621
622  /**
623   * Specifies that each value (not key) stored in the cache should be wrapped in a {@link
624   * WeakReference} (by default, strong references are used).
625   *
626   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
627   * candidate for caching; consider {@link #softValues} instead.
628   *
629   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
630   * comparison to determine equality of values.
631   *
632   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
633   * but will never be visible to read or write operations; such entries are cleaned up as part of
634   * the routine maintenance described in the class javadoc.
635   *
636   * @return this {@code CacheBuilder} instance (for chaining)
637   * @throws IllegalStateException if the value strength was already set
638   */
639  @GwtIncompatible // java.lang.ref.WeakReference
640  public CacheBuilder<K, V> weakValues() {
641    return setValueStrength(Strength.WEAK);
642  }
643
644  /**
645   * Specifies that each value (not key) stored in the cache should be wrapped in a {@link
646   * SoftReference} (by default, strong references are used). Softly-referenced objects will be
647   * garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
648   * demand.
649   *
650   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
651   * #maximumSize(long) maximum size} instead of using soft references. You should only use this
652   * method if you are well familiar with the practical consequences of soft references.
653   *
654   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
655   * comparison to determine equality of values.
656   *
657   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
658   * but will never be visible to read or write operations; such entries are cleaned up as part of
659   * the routine maintenance described in the class javadoc.
660   *
661   * @return this {@code CacheBuilder} instance (for chaining)
662   * @throws IllegalStateException if the value strength was already set
663   */
664  @GwtIncompatible // java.lang.ref.SoftReference
665  public CacheBuilder<K, V> softValues() {
666    return setValueStrength(Strength.SOFT);
667  }
668
669  CacheBuilder<K, V> setValueStrength(Strength strength) {
670    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
671    valueStrength = checkNotNull(strength);
672    return this;
673  }
674
675  Strength getValueStrength() {
676    return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
677  }
678
679  /**
680   * Specifies that each entry should be automatically removed from the cache once a fixed duration
681   * has elapsed after the entry's creation, or the most recent replacement of its value.
682   *
683   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
684   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
685   * useful in testing, or to disable caching temporarily without a code change.
686   *
687   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
688   * write operations. Expired entries are cleaned up as part of the routine maintenance described
689   * in the class javadoc.
690   *
691   * @param duration the length of time after an entry is created that it should be automatically
692   *     removed
693   * @param unit the unit that {@code duration} is expressed in
694   * @return this {@code CacheBuilder} instance (for chaining)
695   * @throws IllegalArgumentException if {@code duration} is negative
696   * @throws IllegalStateException if {@link #expireAfterWrite} was already set
697   */
698  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
699  public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
700    checkState(
701        expireAfterWriteNanos == UNSET_INT,
702        "expireAfterWrite was already set to %s ns",
703        expireAfterWriteNanos);
704    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
705    this.expireAfterWriteNanos = unit.toNanos(duration);
706    return this;
707  }
708
709  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
710  long getExpireAfterWriteNanos() {
711    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
712  }
713
714  /**
715   * Specifies that each entry should be automatically removed from the cache once a fixed duration
716   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
717   * access. Access time is reset by all cache read and write operations (including {@code
718   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
719   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}. So, for
720   * example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for the
721   * entries you retrieve.
722   *
723   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
724   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
725   * useful in testing, or to disable caching temporarily without a code change.
726   *
727   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
728   * write operations. Expired entries are cleaned up as part of the routine maintenance described
729   * in the class javadoc.
730   *
731   * @param duration the length of time after an entry is last accessed that it should be
732   *     automatically removed
733   * @param unit the unit that {@code duration} is expressed in
734   * @return this {@code CacheBuilder} instance (for chaining)
735   * @throws IllegalArgumentException if {@code duration} is negative
736   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
737   */
738  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
739  public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
740    checkState(
741        expireAfterAccessNanos == UNSET_INT,
742        "expireAfterAccess was already set to %s ns",
743        expireAfterAccessNanos);
744    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
745    this.expireAfterAccessNanos = unit.toNanos(duration);
746    return this;
747  }
748
749  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
750  long getExpireAfterAccessNanos() {
751    return (expireAfterAccessNanos == UNSET_INT)
752        ? DEFAULT_EXPIRATION_NANOS
753        : expireAfterAccessNanos;
754  }
755
756  /**
757   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
758   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
759   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
760   * CacheLoader#reload}.
761   *
762   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
763   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
764   * implementation; otherwise refreshes will be performed during unrelated cache read and write
765   * operations.
766   *
767   * <p>Currently automatic refreshes are performed when the first stale request for an entry
768   * occurs. The request triggering refresh will make a synchronous call to {@link
769   * CacheLoader#reload}
770   * and immediately return the new value if the returned future is complete, and the old value
771   * otherwise.
772   *
773   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
774   *
775   * @param duration the length of time after an entry is created that it should be considered
776   *     stale, and thus eligible for refresh
777   * @param unit the unit that {@code duration} is expressed in
778   * @return this {@code CacheBuilder} instance (for chaining)
779   * @throws IllegalArgumentException if {@code duration} is negative
780   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
781   * @since 11.0
782   */
783  @GwtIncompatible // To be supported (synchronously).
784  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
785  public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
786    checkNotNull(unit);
787    checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
788    checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
789    this.refreshNanos = unit.toNanos(duration);
790    return this;
791  }
792
793  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
794  long getRefreshNanos() {
795    return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
796  }
797
798  /**
799   * Specifies a nanosecond-precision time source for this cache. By default, {@link
800   * System#nanoTime} is used.
801   *
802   * <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
803   * time source.
804   *
805   * @return this {@code CacheBuilder} instance (for chaining)
806   * @throws IllegalStateException if a ticker was already set
807   */
808  public CacheBuilder<K, V> ticker(Ticker ticker) {
809    checkState(this.ticker == null);
810    this.ticker = checkNotNull(ticker);
811    return this;
812  }
813
814  Ticker getTicker(boolean recordsTime) {
815    if (ticker != null) {
816      return ticker;
817    }
818    return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
819  }
820
821  /**
822   * Specifies a listener instance that caches should notify each time an entry is removed for any
823   * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
824   * as part of the routine maintenance described in the class documentation above.
825   *
826   * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
827   * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
828   * same instance, but only the returned reference has the correct generic type information so as
829   * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in
830   * the class documentation above, configuring a builder and building your cache in a single
831   * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown
832   * by a cache operation at some <i>undefined</i> point in the future.
833   *
834   * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
835   * the {@code Cache} user, only logged via a {@link Logger}.
836   *
837   * @return the cache builder reference that should be used instead of {@code this} for any
838   *     remaining configuration and cache building
839   * @return this {@code CacheBuilder} instance (for chaining)
840   * @throws IllegalStateException if a removal listener was already set
841   */
842  @CheckReturnValue
843  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
844      RemovalListener<? super K1, ? super V1> listener) {
845    checkState(this.removalListener == null);
846
847    // safely limiting the kinds of caches this can produce
848    @SuppressWarnings("unchecked")
849    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
850    me.removalListener = checkNotNull(listener);
851    return me;
852  }
853
854  // Make a safe contravariant cast now so we don't have to do it over and over.
855  @SuppressWarnings("unchecked")
856  <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
857    return (RemovalListener<K1, V1>)
858        MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
859  }
860
861  /**
862   * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
863   * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
864   * bookkeeping to be performed with each operation, and thus imposes a performance penalty on
865   * cache operation.
866   *
867   * @return this {@code CacheBuilder} instance (for chaining)
868   * @since 12.0 (previously, stats collection was automatic)
869   */
870  public CacheBuilder<K, V> recordStats() {
871    statsCounterSupplier = CACHE_STATS_COUNTER;
872    return this;
873  }
874
875  boolean isRecordingStats() {
876    return statsCounterSupplier == CACHE_STATS_COUNTER;
877  }
878
879  Supplier<? extends StatsCounter> getStatsCounterSupplier() {
880    return statsCounterSupplier;
881  }
882
883  /**
884   * Builds a cache, which either returns an already-loaded value for a given key or atomically
885   * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
886   * loading the value for this key, simply waits for that thread to finish and returns its loaded
887   * value. Note that multiple threads can concurrently load values for distinct keys.
888   *
889   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
890   * invoked again to create multiple independent caches.
891   *
892   * @param loader the cache loader used to obtain new values
893   * @return a cache having the requested features
894   */
895  @CheckReturnValue
896  public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
897      CacheLoader<? super K1, V1> loader) {
898    checkWeightWithWeigher();
899    return new LocalCache.LocalLoadingCache<>(this, loader);
900  }
901
902  /**
903   * Builds a cache which does not automatically load values when keys are requested.
904   *
905   * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code
906   * CacheLoader}.
907   *
908   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
909   * invoked again to create multiple independent caches.
910   *
911   * @return a cache having the requested features
912   * @since 11.0
913   */
914  @CheckReturnValue
915  public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
916    checkWeightWithWeigher();
917    checkNonLoadingCache();
918    return new LocalCache.LocalManualCache<>(this);
919  }
920
921  private void checkNonLoadingCache() {
922    checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
923  }
924
925  private void checkWeightWithWeigher() {
926    if (weigher == null) {
927      checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
928    } else {
929      if (strictParsing) {
930        checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
931      } else {
932        if (maximumWeight == UNSET_INT) {
933          logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
934        }
935      }
936    }
937  }
938
939  /**
940   * Returns a string representation for this CacheBuilder instance. The exact form of the returned
941   * string is not specified.
942   */
943  @Override
944  public String toString() {
945    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
946    if (initialCapacity != UNSET_INT) {
947      s.add("initialCapacity", initialCapacity);
948    }
949    if (concurrencyLevel != UNSET_INT) {
950      s.add("concurrencyLevel", concurrencyLevel);
951    }
952    if (maximumSize != UNSET_INT) {
953      s.add("maximumSize", maximumSize);
954    }
955    if (maximumWeight != UNSET_INT) {
956      s.add("maximumWeight", maximumWeight);
957    }
958    if (expireAfterWriteNanos != UNSET_INT) {
959      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
960    }
961    if (expireAfterAccessNanos != UNSET_INT) {
962      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
963    }
964    if (keyStrength != null) {
965      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
966    }
967    if (valueStrength != null) {
968      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
969    }
970    if (keyEquivalence != null) {
971      s.addValue("keyEquivalence");
972    }
973    if (valueEquivalence != null) {
974      s.addValue("valueEquivalence");
975    }
976    if (removalListener != null) {
977      s.addValue("removalListener");
978    }
979    return s.toString();
980  }
981}