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