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