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