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