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