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