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