001/*
002 * Copyright (C) 2009 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.cache;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.base.Ascii;
024import com.google.common.base.Equivalence;
025import com.google.common.base.MoreObjects;
026import com.google.common.base.Supplier;
027import com.google.common.base.Suppliers;
028import com.google.common.base.Ticker;
029import com.google.common.cache.AbstractCache.SimpleStatsCounter;
030import com.google.common.cache.AbstractCache.StatsCounter;
031import com.google.common.cache.LocalCache.Strength;
032import com.google.errorprone.annotations.CheckReturnValue;
033import com.google.j2objc.annotations.J2ObjCIncompatible;
034import java.util.ConcurrentModificationException;
035import java.util.IdentityHashMap;
036import java.util.Map;
037import java.util.concurrent.ConcurrentHashMap;
038import java.util.concurrent.TimeUnit;
039import java.util.logging.Level;
040import java.util.logging.Logger;
041import org.checkerframework.checker.nullness.qual.Nullable;
042
043/**
044 * A builder of {@link LoadingCache} and {@link Cache} instances.
045 *
046 * <h2>Prefer <a href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a> over Guava's caching
047 * API</h2>
048 *
049 * <p>The successor to Guava's caching API is <a
050 * href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>. Its API is designed to make it a
051 * nearly drop-in replacement -- though it requires Java 8 APIs and is not available for Android or
052 * GWT/j2cl. Its equivalent to {@code CacheBuilder} is its <a
053 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html">{@code
054 * Caffeine}</a> class. Caffeine offers better performance, more features (including asynchronous
055 * loading), and fewer <a
056 * href="https://github.com/google/guava/issues?q=is%3Aopen+is%3Aissue+label%3Apackage%3Dcache+label%3Atype%3Ddefect">bugs</a>.
057 *
058 * <p>Caffeine defines its own interfaces (<a
059 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Cache.html">{@code
060 * Cache}</a>, <a
061 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/LoadingCache.html">{@code
062 * LoadingCache}</a>, <a
063 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/CacheLoader.html">{@code
064 * CacheLoader}</a>, etc.), so you can use Caffeine without needing to use any Guava types.
065 * Caffeine's types are better than Guava's, especially for <a
066 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html">their
067 * deep support for asynchronous operations</a>. But if you want to migrate to Caffeine with minimal
068 * code changes, you can use <a
069 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/guava/latest/com.github.benmanes.caffeine.guava/com/github/benmanes/caffeine/guava/CaffeinatedGuava.html">its
070 * {@code CaffeinatedGuava} adapter class</a>, which lets you build a Guava {@code Cache} or a Guava
071 * {@code LoadingCache} backed by a Guava {@code CacheLoader}.
072 *
073 * <p>Caffeine's API for asynchronous operations uses {@code CompletableFuture}: <a
074 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html#get(K)">{@code
075 * AsyncLoadingCache.get}</a> returns a {@code CompletableFuture}, and implementations of <a
076 * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncCacheLoader.html#asyncLoad(K,java.util.concurrent.Executor)">{@code
077 * AsyncCacheLoader.asyncLoad}</a> must return a {@code CompletableFuture}. Users of Guava's {@link
078 * com.google.common.util.concurrent.ListenableFuture} can adapt between the two {@code Future}
079 * types by using <a href="https://github.com/lukas-krecan/future-converter#java8-guava">{@code
080 * net.javacrumbs.futureconverter.java8guava.FutureConverter}</a>.
081 *
082 * <h2>More on {@code CacheBuilder}</h2>
083 *
084 * {@code CacheBuilder} builds caches with any combination of the following features:
085 *
086 * <ul>
087 *   <li>automatic loading of entries into the cache
088 *   <li>least-recently-used eviction when a maximum size is exceeded (note that the cache is
089 *       divided into segments, each of which does LRU internally)
090 *   <li>time-based expiration of entries, measured since last access or last write
091 *   <li>keys automatically wrapped in {@code WeakReference}
092 *   <li>values automatically wrapped in {@code WeakReference} or {@code SoftReference}
093 *   <li>notification of evicted (or otherwise removed) entries
094 *   <li>accumulation of cache access statistics
095 * </ul>
096 *
097 * <p>These features are all optional; caches can be created using all or none of them. By default
098 * cache instances created by {@code CacheBuilder} will not perform any type of eviction.
099 *
100 * <p>Usage example:
101 *
102 * <pre>{@code
103 * LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
104 *     .maximumSize(10000)
105 *     .expireAfterWrite(Duration.ofMinutes(10))
106 *     .removalListener(MY_LISTENER)
107 *     .build(
108 *         new CacheLoader<Key, Graph>() {
109 *           public Graph load(Key key) throws AnyException {
110 *             return createExpensiveGraph(key);
111 *           }
112 *         });
113 * }</pre>
114 *
115 * <p>Or equivalently,
116 *
117 * <pre>{@code
118 * // In real life this would come from a command-line flag or config file
119 * String spec = "maximumSize=10000,expireAfterWrite=10m";
120 *
121 * LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
122 *     .removalListener(MY_LISTENER)
123 *     .build(
124 *         new CacheLoader<Key, Graph>() {
125 *           public Graph load(Key key) throws AnyException {
126 *             return createExpensiveGraph(key);
127 *           }
128 *         });
129 * }</pre>
130 *
131 * <p>The returned cache is implemented as a hash table with similar performance characteristics to
132 * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
133 * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
134 * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
135 * modify the cache after the iterator is created, it is undefined which of these changes, if any,
136 * are reflected in that iterator. These iterators never throw {@link
137 * ConcurrentModificationException}.
138 *
139 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link
140 * Object#equals equals} method) to determine equality for keys or values. However, if {@link
141 * #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for keys.
142 * Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity
143 * comparisons for values.
144 *
145 * <p>Entries are automatically evicted from the cache when any of {@linkplain #maximumSize(long)
146 * maximumSize}, {@linkplain #maximumWeight(long) maximumWeight}, {@linkplain #expireAfterWrite
147 * expireAfterWrite}, {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys
148 * weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are
149 * requested.
150 *
151 * <p>If {@linkplain #maximumSize(long) maximumSize} or {@linkplain #maximumWeight(long)
152 * maximumWeight} is requested entries may be evicted on each cache modification.
153 *
154 * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or {@linkplain #expireAfterAccess
155 * expireAfterAccess} is requested entries may be evicted on each cache modification, on occasional
156 * cache accesses, or on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link
157 * Cache#size}, but will never be visible to read or write operations.
158 *
159 * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or {@linkplain
160 * #softValues softValues} are requested, it is possible for a key or value present in the cache to
161 * be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from
162 * the cache on each cache modification, on occasional cache accesses, or on calls to {@link
163 * Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be visible to
164 * read or write operations.
165 *
166 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
167 * will be performed during write operations, or during occasional read operations in the absence of
168 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
169 * calling it should not be necessary with a high throughput cache. Only caches built with
170 * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
171 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys}, {@linkplain
172 * #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic maintenance.
173 *
174 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
175 * retain all the configuration properties of the original cache. Note that the serialized form does
176 * <i>not</i> include cache contents, but only configuration.
177 *
178 * <p>See the Guava User Guide article on <a
179 * href="https://github.com/google/guava/wiki/CachesExplained">caching</a> for a higher-level
180 * explanation.
181 *
182 * @param <K> the most general key type this builder will be able to create caches for. This is
183 *     normally {@code Object} unless it is constrained by using a method like {@code
184 *     #removalListener}. Cache keys may not be null.
185 * @param <V> the most general value type this builder will be able to create caches for. This is
186 *     normally {@code Object} unless it is constrained by using a method like {@code
187 *     #removalListener}. Cache values may not be null.
188 * @author Charles Fry
189 * @author Kevin Bourrillion
190 * @since 10.0
191 */
192@GwtCompatible(emulated = true)
193@ElementTypesAreNonnullByDefault
194public final class CacheBuilder<K, V> {
195  private static final int DEFAULT_INITIAL_CAPACITY = 16;
196  private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
197
198  @SuppressWarnings("GoodTime") // should be a java.time.Duration
199  private static final int DEFAULT_EXPIRATION_NANOS = 0;
200
201  @SuppressWarnings("GoodTime") // should be a java.time.Duration
202  private static final int DEFAULT_REFRESH_NANOS = 0;
203
204  static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER =
205      Suppliers.ofInstance(
206          new StatsCounter() {
207            @Override
208            public void recordHits(int count) {}
209
210            @Override
211            public void recordMisses(int count) {}
212
213            @SuppressWarnings("GoodTime") // b/122668874
214            @Override
215            public void recordLoadSuccess(long loadTime) {}
216
217            @SuppressWarnings("GoodTime") // b/122668874
218            @Override
219            public void recordLoadException(long loadTime) {}
220
221            @Override
222            public void recordEviction() {}
223
224            @Override
225            public CacheStats snapshot() {
226              return EMPTY_STATS;
227            }
228          });
229  static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
230
231  static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
232      new Supplier<StatsCounter>() {
233        @Override
234        public StatsCounter get() {
235          return new SimpleStatsCounter();
236        }
237      };
238
239  enum NullListener implements RemovalListener<Object, Object> {
240    INSTANCE;
241
242    @Override
243    public void onRemoval(RemovalNotification<Object, Object> notification) {}
244  }
245
246  enum OneWeigher implements Weigher<Object, Object> {
247    INSTANCE;
248
249    @Override
250    public int weigh(Object key, Object value) {
251      return 1;
252    }
253  }
254
255  static final Ticker NULL_TICKER =
256      new Ticker() {
257        @Override
258        public long read() {
259          return 0;
260        }
261      };
262
263  private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
264
265  static final int UNSET_INT = -1;
266
267  boolean strictParsing = true;
268
269  int initialCapacity = UNSET_INT;
270  int concurrencyLevel = UNSET_INT;
271  long maximumSize = UNSET_INT;
272  long maximumWeight = UNSET_INT;
273  @Nullable Weigher<? super K, ? super V> weigher;
274
275  @Nullable Strength keyStrength;
276  @Nullable Strength valueStrength;
277
278  @SuppressWarnings("GoodTime") // should be a java.time.Duration
279  long expireAfterWriteNanos = UNSET_INT;
280
281  @SuppressWarnings("GoodTime") // should be a java.time.Duration
282  long expireAfterAccessNanos = UNSET_INT;
283
284  @SuppressWarnings("GoodTime") // should be a java.time.Duration
285  long refreshNanos = UNSET_INT;
286
287  @Nullable Equivalence<Object> keyEquivalence;
288  @Nullable Equivalence<Object> valueEquivalence;
289
290  @Nullable RemovalListener<? super K, ? super V> removalListener;
291  @Nullable Ticker ticker;
292
293  Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
294
295  private CacheBuilder() {}
296
297  /**
298   * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
299   * strong values, and no automatic eviction of any kind.
300   *
301   * <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on
302   * the {@link #build} methods allow you to create a cache of any key and value type desired.
303   */
304  @CheckReturnValue
305  public static CacheBuilder<Object, Object> newBuilder() {
306    return new CacheBuilder<>();
307  }
308
309  /**
310   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
311   *
312   * @since 12.0
313   */
314  @GwtIncompatible // To be supported
315  @CheckReturnValue
316  public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
317    return spec.toCacheBuilder().lenientParsing();
318  }
319
320  /**
321   * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
322   * This is especially useful for command-line configuration of a {@code CacheBuilder}.
323   *
324   * @param spec a String in the format specified by {@link CacheBuilderSpec}
325   * @since 12.0
326   */
327  @GwtIncompatible // To be supported
328  @CheckReturnValue
329  public static CacheBuilder<Object, Object> from(String spec) {
330    return from(CacheBuilderSpec.parse(spec));
331  }
332
333  /**
334   * Enables lenient parsing. Useful for tests and spec parsing.
335   *
336   * @return this {@code CacheBuilder} instance (for chaining)
337   */
338  @GwtIncompatible // To be supported
339  CacheBuilder<K, V> lenientParsing() {
340    strictParsing = false;
341    return this;
342  }
343
344  /**
345   * Sets a custom {@code Equivalence} strategy for comparing keys.
346   *
347   * <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
348   * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
349   *
350   * @return this {@code CacheBuilder} instance (for chaining)
351   */
352  @GwtIncompatible // To be supported
353  CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
354    checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
355    keyEquivalence = checkNotNull(equivalence);
356    return this;
357  }
358
359  Equivalence<Object> getKeyEquivalence() {
360    return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
361  }
362
363  /**
364   * Sets a custom {@code Equivalence} strategy for comparing values.
365   *
366   * <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
367   * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()}
368   * otherwise.
369   *
370   * @return this {@code CacheBuilder} instance (for chaining)
371   */
372  @GwtIncompatible // To be supported
373  CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
374    checkState(
375        valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence);
376    this.valueEquivalence = checkNotNull(equivalence);
377    return this;
378  }
379
380  Equivalence<Object> getValueEquivalence() {
381    return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
382  }
383
384  /**
385   * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
386   * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
387   * having a hash table of size eight. Providing a large enough estimate at construction time
388   * avoids the need for expensive resizing operations later, but setting this value unnecessarily
389   * high wastes memory.
390   *
391   * @return this {@code CacheBuilder} instance (for chaining)
392   * @throws IllegalArgumentException if {@code initialCapacity} is negative
393   * @throws IllegalStateException if an initial capacity was already set
394   */
395  public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
396    checkState(
397        this.initialCapacity == UNSET_INT,
398        "initial capacity was already set to %s",
399        this.initialCapacity);
400    checkArgument(initialCapacity >= 0);
401    this.initialCapacity = initialCapacity;
402    return this;
403  }
404
405  int getInitialCapacity() {
406    return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
407  }
408
409  /**
410   * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
411   * table is internally partitioned to try to permit the indicated number of concurrent updates
412   * without contention. Because assignment of entries to these partitions is not necessarily
413   * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
414   * accommodate as many threads as will ever concurrently modify the table. Using a significantly
415   * higher value than you need can waste space and time, and a significantly lower value can lead
416   * to thread contention. But overestimates and underestimates within an order of magnitude do not
417   * usually have much noticeable impact. A value of one permits only one thread to modify the cache
418   * at a time, but since read operations and cache loading computations can proceed concurrently,
419   * this still yields higher concurrency than full synchronization.
420   *
421   * <p>Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
422   * value, you should always choose it explicitly.
423   *
424   * <p>The current implementation uses the concurrency level to create a fixed number of hashtable
425   * segments, each governed by its own write lock. The segment lock is taken once for each explicit
426   * write, and twice for each cache loading computation (once prior to loading the new value, and
427   * once after loading completes). Much internal cache management is performed at the segment
428   * granularity. For example, access queues and write queues are kept per segment when they are
429   * required by the selected eviction algorithm. As such, when writing unit tests it is not
430   * uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
431   * behavior.
432   *
433   * <p>Note that future implementations may abandon segment locking in favor of more advanced
434   * concurrency controls.
435   *
436   * @return this {@code CacheBuilder} instance (for chaining)
437   * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
438   * @throws IllegalStateException if a concurrency level was already set
439   */
440  public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
441    checkState(
442        this.concurrencyLevel == UNSET_INT,
443        "concurrency level was already set to %s",
444        this.concurrencyLevel);
445    checkArgument(concurrencyLevel > 0);
446    this.concurrencyLevel = concurrencyLevel;
447    return this;
448  }
449
450  int getConcurrencyLevel() {
451    return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
452  }
453
454  /**
455   * Specifies the maximum number of entries the cache may contain.
456   *
457   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
458   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
459   * resulting segment inside the cache <i>independently</i> limits its own size to approximately
460   * {@code maximumSize / concurrencyLevel}.
461   *
462   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
463   * For example, the cache may evict an entry because it hasn't been used recently or very often.
464   *
465   * <p>If {@code maximumSize} is zero, elements will be evicted immediately after being loaded into
466   * cache. This can be useful in testing, or to disable caching temporarily.
467   *
468   * <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
469   *
470   * @param maximumSize the maximum size of the cache
471   * @return this {@code CacheBuilder} instance (for chaining)
472   * @throws IllegalArgumentException if {@code maximumSize} is negative
473   * @throws IllegalStateException if a maximum size or weight was already set
474   */
475  public CacheBuilder<K, V> maximumSize(long maximumSize) {
476    checkState(
477        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
478    checkState(
479        this.maximumWeight == UNSET_INT,
480        "maximum weight was already set to %s",
481        this.maximumWeight);
482    checkState(this.weigher == null, "maximum size can not be combined with weigher");
483    checkArgument(maximumSize >= 0, "maximum size must not be negative");
484    this.maximumSize = maximumSize;
485    return this;
486  }
487
488  /**
489   * Specifies the maximum weight of entries the cache may contain. Weight is determined using the
490   * {@link Weigher} specified with {@link #weigher}, and use of this method requires a
491   * corresponding call to {@link #weigher} prior to calling {@link #build}.
492   *
493   * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
494   * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
495   * resulting segment inside the cache <i>independently</i> limits its own weight to approximately
496   * {@code maximumWeight / concurrencyLevel}.
497   *
498   * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again.
499   * For example, the cache may evict an entry because it hasn't been used recently or very often.
500   *
501   * <p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded
502   * into cache. This can be useful in testing, or to disable caching temporarily.
503   *
504   * <p>Note that weight is only used to determine whether the cache is over capacity; it has no
505   * effect on selecting which entry should be evicted next.
506   *
507   * <p>This feature cannot be used in conjunction with {@link #maximumSize}.
508   *
509   * @param maximumWeight the maximum total weight of entries the cache may contain
510   * @return this {@code CacheBuilder} instance (for chaining)
511   * @throws IllegalArgumentException if {@code maximumWeight} is negative
512   * @throws IllegalStateException if a maximum weight or size was already set
513   * @since 11.0
514   */
515  @GwtIncompatible // To be supported
516  public CacheBuilder<K, V> maximumWeight(long maximumWeight) {
517    checkState(
518        this.maximumWeight == UNSET_INT,
519        "maximum weight was already set to %s",
520        this.maximumWeight);
521    checkState(
522        this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
523    checkArgument(maximumWeight >= 0, "maximum weight must not be negative");
524    this.maximumWeight = maximumWeight;
525    return this;
526  }
527
528  /**
529   * Specifies the weigher to use in determining the weight of entries. Entry weight is taken into
530   * consideration by {@link #maximumWeight(long)} when determining which entries to evict, and use
531   * of this method requires a corresponding call to {@link #maximumWeight(long)} prior to calling
532   * {@link #build}. Weights are measured and recorded when entries are inserted into the cache, and
533   * are thus effectively static during the lifetime of a cache entry.
534   *
535   * <p>When the weight of an entry is zero it will not be considered for size-based eviction
536   * (though it still may be evicted by other means).
537   *
538   * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
539   * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
540   * original reference or the returned reference may be used to complete configuration and build
541   * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
542   * building caches whose key or value types are incompatible with the types accepted by the
543   * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
544   * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
545   * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
546   *
547   * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build a
548   * cache whose key or value type is incompatible with the weigher, you will likely experience a
549   * {@link ClassCastException} at some <i>undefined</i> point in the future.
550   *
551   * @param weigher the weigher to use in calculating the weight of cache entries
552   * @return this {@code CacheBuilder} instance (for chaining)
553   * @throws IllegalArgumentException if {@code size} is negative
554   * @throws IllegalStateException if a maximum size was already set
555   * @since 11.0
556   */
557  @GwtIncompatible // To be supported
558  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
559      Weigher<? super K1, ? super V1> weigher) {
560    checkState(this.weigher == null);
561    if (strictParsing) {
562      checkState(
563          this.maximumSize == UNSET_INT,
564          "weigher can not be combined with maximum size",
565          this.maximumSize);
566    }
567
568    // safely limiting the kinds of caches this can produce
569    @SuppressWarnings("unchecked")
570    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
571    me.weigher = checkNotNull(weigher);
572    return me;
573  }
574
575  long getMaximumWeight() {
576    if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
577      return 0;
578    }
579    return (weigher == null) ? maximumSize : maximumWeight;
580  }
581
582  // Make a safe contravariant cast now so we don't have to do it over and over.
583  @SuppressWarnings("unchecked")
584  <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
585    return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
586  }
587
588  /**
589   * Specifies that each key (not value) stored in the cache should be wrapped in a {@link
590   * WeakReference} (by default, strong references are used).
591   *
592   * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
593   * comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore
594   * technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap}
595   * does).
596   *
597   * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size}, but
598   * will never be visible to read or write operations; such entries are cleaned up as part of the
599   * routine maintenance described in the class javadoc.
600   *
601   * @return this {@code CacheBuilder} instance (for chaining)
602   * @throws IllegalStateException if the key strength was already set
603   */
604  @GwtIncompatible // java.lang.ref.WeakReference
605  public CacheBuilder<K, V> weakKeys() {
606    return setKeyStrength(Strength.WEAK);
607  }
608
609  CacheBuilder<K, V> setKeyStrength(Strength strength) {
610    checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
611    keyStrength = checkNotNull(strength);
612    return this;
613  }
614
615  Strength getKeyStrength() {
616    return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
617  }
618
619  /**
620   * Specifies that each value (not key) stored in the cache should be wrapped in a {@link
621   * WeakReference} (by default, strong references are used).
622   *
623   * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
624   * candidate for caching; consider {@link #softValues} instead.
625   *
626   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
627   * comparison to determine equality of values.
628   *
629   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
630   * but will never be visible to read or write operations; such entries are cleaned up as part of
631   * the routine maintenance described in the class javadoc.
632   *
633   * @return this {@code CacheBuilder} instance (for chaining)
634   * @throws IllegalStateException if the value strength was already set
635   */
636  @GwtIncompatible // java.lang.ref.WeakReference
637  public CacheBuilder<K, V> weakValues() {
638    return setValueStrength(Strength.WEAK);
639  }
640
641  /**
642   * Specifies that each value (not key) stored in the cache should be wrapped in a {@link
643   * SoftReference} (by default, strong references are used). Softly-referenced objects will be
644   * garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
645   * demand.
646   *
647   * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
648   * #maximumSize(long) maximum size} instead of using soft references. You should only use this
649   * method if you are well familiar with the practical consequences of soft references.
650   *
651   * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
652   * comparison to determine equality of values.
653   *
654   * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
655   * but will never be visible to read or write operations; such entries are cleaned up as part of
656   * the routine maintenance described in the class javadoc.
657   *
658   * @return this {@code CacheBuilder} instance (for chaining)
659   * @throws IllegalStateException if the value strength was already set
660   */
661  @GwtIncompatible // java.lang.ref.SoftReference
662  public CacheBuilder<K, V> softValues() {
663    return setValueStrength(Strength.SOFT);
664  }
665
666  CacheBuilder<K, V> setValueStrength(Strength strength) {
667    checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
668    valueStrength = checkNotNull(strength);
669    return this;
670  }
671
672  Strength getValueStrength() {
673    return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
674  }
675
676  /**
677   * Specifies that each entry should be automatically removed from the cache once a fixed duration
678   * has elapsed after the entry's creation, or the most recent replacement of its value.
679   *
680   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
681   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
682   * useful in testing, or to disable caching temporarily without a code change.
683   *
684   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
685   * write operations. Expired entries are cleaned up as part of the routine maintenance described
686   * in the class javadoc.
687   *
688   * @param duration the length of time after an entry is created that it should be automatically
689   *     removed
690   * @return this {@code CacheBuilder} instance (for chaining)
691   * @throws IllegalArgumentException if {@code duration} is negative
692   * @throws IllegalStateException if {@link #expireAfterWrite} was already set
693   * @throws ArithmeticException for durations greater than +/- approximately 292 years
694   * @since 25.0
695   */
696  @J2ObjCIncompatible
697  @GwtIncompatible // java.time.Duration
698  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
699  public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) {
700    return expireAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
701  }
702
703  /**
704   * Specifies that each entry should be automatically removed from the cache once a fixed duration
705   * has elapsed after the entry's creation, or the most recent replacement of its value.
706   *
707   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
708   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
709   * useful in testing, or to disable caching temporarily without a code change.
710   *
711   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
712   * write operations. Expired entries are cleaned up as part of the routine maintenance described
713   * in the class javadoc.
714   *
715   * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
716   * when feasible), use {@link #expireAfterWrite(Duration)} instead.
717   *
718   * @param duration the length of time after an entry is created that it should be automatically
719   *     removed
720   * @param unit the unit that {@code duration} is expressed in
721   * @return this {@code CacheBuilder} instance (for chaining)
722   * @throws IllegalArgumentException if {@code duration} is negative
723   * @throws IllegalStateException if {@link #expireAfterWrite} was already set
724   */
725  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
726  public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
727    checkState(
728        expireAfterWriteNanos == UNSET_INT,
729        "expireAfterWrite was already set to %s ns",
730        expireAfterWriteNanos);
731    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
732    this.expireAfterWriteNanos = unit.toNanos(duration);
733    return this;
734  }
735
736  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
737  long getExpireAfterWriteNanos() {
738    return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
739  }
740
741  /**
742   * Specifies that each entry should be automatically removed from the cache once a fixed duration
743   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
744   * access. Access time is reset by all cache read and write operations (including {@code
745   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
746   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}}. So,
747   * for example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for
748   * the entries you retrieve.
749   *
750   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
751   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
752   * useful in testing, or to disable caching temporarily without a code change.
753   *
754   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
755   * write operations. Expired entries are cleaned up as part of the routine maintenance described
756   * in the class javadoc.
757   *
758   * @param duration the length of time after an entry is last accessed that it should be
759   *     automatically removed
760   * @return this {@code CacheBuilder} instance (for chaining)
761   * @throws IllegalArgumentException if {@code duration} is negative
762   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
763   * @throws ArithmeticException for durations greater than +/- approximately 292 years
764   * @since 25.0
765   */
766  @J2ObjCIncompatible
767  @GwtIncompatible // java.time.Duration
768  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
769  public CacheBuilder<K, V> expireAfterAccess(java.time.Duration duration) {
770    return expireAfterAccess(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
771  }
772
773  /**
774   * Specifies that each entry should be automatically removed from the cache once a fixed duration
775   * has elapsed after the entry's creation, the most recent replacement of its value, or its last
776   * access. Access time is reset by all cache read and write operations (including {@code
777   * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code
778   * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}. So, for
779   * example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for the
780   * entries you retrieve.
781   *
782   * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long)
783   * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be
784   * useful in testing, or to disable caching temporarily without a code change.
785   *
786   * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
787   * write operations. Expired entries are cleaned up as part of the routine maintenance described
788   * in the class javadoc.
789   *
790   * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
791   * when feasible), use {@link #expireAfterAccess(Duration)} instead.
792   *
793   * @param duration the length of time after an entry is last accessed that it should be
794   *     automatically removed
795   * @param unit the unit that {@code duration} is expressed in
796   * @return this {@code CacheBuilder} instance (for chaining)
797   * @throws IllegalArgumentException if {@code duration} is negative
798   * @throws IllegalStateException if {@link #expireAfterAccess} was already set
799   */
800  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
801  public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
802    checkState(
803        expireAfterAccessNanos == UNSET_INT,
804        "expireAfterAccess was already set to %s ns",
805        expireAfterAccessNanos);
806    checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
807    this.expireAfterAccessNanos = unit.toNanos(duration);
808    return this;
809  }
810
811  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
812  long getExpireAfterAccessNanos() {
813    return (expireAfterAccessNanos == UNSET_INT)
814        ? DEFAULT_EXPIRATION_NANOS
815        : expireAfterAccessNanos;
816  }
817
818  /**
819   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
820   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
821   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
822   * CacheLoader#reload}.
823   *
824   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
825   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
826   * implementation; otherwise refreshes will be performed during unrelated cache read and write
827   * operations.
828   *
829   * <p>Currently automatic refreshes are performed when the first stale request for an entry
830   * occurs. The request triggering refresh will make a synchronous call to {@link
831   * CacheLoader#reload}
832   * to obtain a future of the new value. If the returned future is already complete, it is returned
833   * immediately. Otherwise, the old value is returned.
834   *
835   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
836   *
837   * @param duration the length of time after an entry is created that it should be considered
838   *     stale, and thus eligible for refresh
839   * @return this {@code CacheBuilder} instance (for chaining)
840   * @throws IllegalArgumentException if {@code duration} is negative
841   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
842   * @throws ArithmeticException for durations greater than +/- approximately 292 years
843   * @since 25.0
844   */
845  @J2ObjCIncompatible
846  @GwtIncompatible // java.time.Duration
847  @SuppressWarnings("GoodTime") // java.time.Duration decomposition
848  public CacheBuilder<K, V> refreshAfterWrite(java.time.Duration duration) {
849    return refreshAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS);
850  }
851
852  /**
853   * Specifies that active entries are eligible for automatic refresh once a fixed duration has
854   * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
855   * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link
856   * CacheLoader#reload}.
857   *
858   * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
859   * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
860   * implementation; otherwise refreshes will be performed during unrelated cache read and write
861   * operations.
862   *
863   * <p>Currently automatic refreshes are performed when the first stale request for an entry
864   * occurs. The request triggering refresh will make a synchronous call to {@link
865   * CacheLoader#reload}
866   * and immediately return the new value if the returned future is complete, and the old value
867   * otherwise.
868   *
869   * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
870   *
871   * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred
872   * when feasible), use {@link #refreshAfterWrite(Duration)} instead.
873   *
874   * @param duration the length of time after an entry is created that it should be considered
875   *     stale, and thus eligible for refresh
876   * @param unit the unit that {@code duration} is expressed in
877   * @return this {@code CacheBuilder} instance (for chaining)
878   * @throws IllegalArgumentException if {@code duration} is negative
879   * @throws IllegalStateException if {@link #refreshAfterWrite} was already set
880   * @since 11.0
881   */
882  @GwtIncompatible // To be supported (synchronously).
883  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
884  public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
885    checkNotNull(unit);
886    checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
887    checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
888    this.refreshNanos = unit.toNanos(duration);
889    return this;
890  }
891
892  @SuppressWarnings("GoodTime") // nanos internally, should be Duration
893  long getRefreshNanos() {
894    return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
895  }
896
897  /**
898   * Specifies a nanosecond-precision time source for this cache. By default, {@link
899   * System#nanoTime} is used.
900   *
901   * <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
902   * time source.
903   *
904   * @return this {@code CacheBuilder} instance (for chaining)
905   * @throws IllegalStateException if a ticker was already set
906   */
907  public CacheBuilder<K, V> ticker(Ticker ticker) {
908    checkState(this.ticker == null);
909    this.ticker = checkNotNull(ticker);
910    return this;
911  }
912
913  Ticker getTicker(boolean recordsTime) {
914    if (ticker != null) {
915      return ticker;
916    }
917    return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
918  }
919
920  /**
921   * Specifies a listener instance that caches should notify each time an entry is removed for any
922   * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
923   * as part of the routine maintenance described in the class documentation above.
924   *
925   * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder
926   * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the
927   * same instance, but only the returned reference has the correct generic type information so as
928   * to ensure type safety. For best results, use the standard method-chaining idiom illustrated in
929   * the class documentation above, configuring a builder and building your cache in a single
930   * statement. Failure to heed this advice can result in a {@link ClassCastException} being thrown
931   * by a cache operation at some <i>undefined</i> point in the future.
932   *
933   * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
934   * the {@code Cache} user, only logged via a {@link Logger}.
935   *
936   * @return the cache builder reference that should be used instead of {@code this} for any
937   *     remaining configuration and cache building
938   * @return this {@code CacheBuilder} instance (for chaining)
939   * @throws IllegalStateException if a removal listener was already set
940   */
941  @CheckReturnValue
942  public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
943      RemovalListener<? super K1, ? super V1> listener) {
944    checkState(this.removalListener == null);
945
946    // safely limiting the kinds of caches this can produce
947    @SuppressWarnings("unchecked")
948    CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
949    me.removalListener = checkNotNull(listener);
950    return me;
951  }
952
953  // Make a safe contravariant cast now so we don't have to do it over and over.
954  @SuppressWarnings("unchecked")
955  <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
956    return (RemovalListener<K1, V1>)
957        MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
958  }
959
960  /**
961   * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
962   * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
963   * bookkeeping to be performed with each operation, and thus imposes a performance penalty on
964   * cache operation.
965   *
966   * @return this {@code CacheBuilder} instance (for chaining)
967   * @since 12.0 (previously, stats collection was automatic)
968   */
969  public CacheBuilder<K, V> recordStats() {
970    statsCounterSupplier = CACHE_STATS_COUNTER;
971    return this;
972  }
973
974  boolean isRecordingStats() {
975    return statsCounterSupplier == CACHE_STATS_COUNTER;
976  }
977
978  Supplier<? extends StatsCounter> getStatsCounterSupplier() {
979    return statsCounterSupplier;
980  }
981
982  /**
983   * Builds a cache, which either returns an already-loaded value for a given key or atomically
984   * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
985   * loading the value for this key, simply waits for that thread to finish and returns its loaded
986   * value. Note that multiple threads can concurrently load values for distinct keys.
987   *
988   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
989   * invoked again to create multiple independent caches.
990   *
991   * @param loader the cache loader used to obtain new values
992   * @return a cache having the requested features
993   */
994  @CheckReturnValue
995  public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
996      CacheLoader<? super K1, V1> loader) {
997    checkWeightWithWeigher();
998    return new LocalCache.LocalLoadingCache<>(this, loader);
999  }
1000
1001  /**
1002   * Builds a cache which does not automatically load values when keys are requested.
1003   *
1004   * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code
1005   * CacheLoader}.
1006   *
1007   * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
1008   * invoked again to create multiple independent caches.
1009   *
1010   * @return a cache having the requested features
1011   * @since 11.0
1012   */
1013  @CheckReturnValue
1014  public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
1015    checkWeightWithWeigher();
1016    checkNonLoadingCache();
1017    return new LocalCache.LocalManualCache<>(this);
1018  }
1019
1020  private void checkNonLoadingCache() {
1021    checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
1022  }
1023
1024  private void checkWeightWithWeigher() {
1025    if (weigher == null) {
1026      checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
1027    } else {
1028      if (strictParsing) {
1029        checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
1030      } else {
1031        if (maximumWeight == UNSET_INT) {
1032          logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
1033        }
1034      }
1035    }
1036  }
1037
1038  /**
1039   * Returns a string representation for this CacheBuilder instance. The exact form of the returned
1040   * string is not specified.
1041   */
1042  @Override
1043  public String toString() {
1044    MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
1045    if (initialCapacity != UNSET_INT) {
1046      s.add("initialCapacity", initialCapacity);
1047    }
1048    if (concurrencyLevel != UNSET_INT) {
1049      s.add("concurrencyLevel", concurrencyLevel);
1050    }
1051    if (maximumSize != UNSET_INT) {
1052      s.add("maximumSize", maximumSize);
1053    }
1054    if (maximumWeight != UNSET_INT) {
1055      s.add("maximumWeight", maximumWeight);
1056    }
1057    if (expireAfterWriteNanos != UNSET_INT) {
1058      s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
1059    }
1060    if (expireAfterAccessNanos != UNSET_INT) {
1061      s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
1062    }
1063    if (keyStrength != null) {
1064      s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
1065    }
1066    if (valueStrength != null) {
1067      s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
1068    }
1069    if (keyEquivalence != null) {
1070      s.addValue("keyEquivalence");
1071    }
1072    if (valueEquivalence != null) {
1073      s.addValue("valueEquivalence");
1074    }
1075    if (removalListener != null) {
1076      s.addValue("removalListener");
1077    }
1078    return s.toString();
1079  }
1080
1081  /**
1082   * Returns the number of nanoseconds of the given duration without throwing or overflowing.
1083   *
1084   * <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either
1085   * {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing
1086   * a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair.
1087   */
1088  @GwtIncompatible // java.time.Duration
1089  @SuppressWarnings("GoodTime") // duration decomposition
1090  private static long toNanosSaturated(java.time.Duration duration) {
1091    // Using a try/catch seems lazy, but the catch block will rarely get invoked (except for
1092    // durations longer than approximately +/- 292 years).
1093    try {
1094      return duration.toNanos();
1095    } catch (ArithmeticException tooBig) {
1096      return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE;
1097    }
1098  }
1099}