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