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