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