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