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