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