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