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