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