org.glassfish.jersey.internal.guava.CacheBuilder Maven / Gradle / Ivy
Show all versions of jaxrs-ri Show documentation
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glassfish.jersey.internal.guava;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ConcurrentModificationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import static org.glassfish.jersey.internal.guava.Preconditions.checkArgument;
import static org.glassfish.jersey.internal.guava.Preconditions.checkState;
/**
* A builder of {@link LoadingCache} and {@link Cache} instances having any combination of the
* following features:
*
*
* - automatic loading of entries into the cache
*
- least-recently-used eviction when a maximum size is exceeded
*
- time-based expiration of entries, measured since last access or last write
*
- keys automatically wrapped in {@linkplain WeakReference weak} references
*
- values automatically wrapped in {@linkplain WeakReference weak} or
* {@linkplain SoftReference soft} references
*
- notification of evicted (or otherwise removed) entries
*
- accumulation of cache access statistics
*
*
*
These features are all optional; caches can be created using all or none of them. By default
* cache instances created by {@code CacheBuilder} will not perform any type of eviction.
*
*
Usage example:
{@code
*
* LoadingCache graphs = CacheBuilder.newBuilder()
* .maximumSize(10000)
* .expireAfterWrite(10, TimeUnit.MINUTES)
* .removalListener(MY_LISTENER)
* .build(
* new CacheLoader() {
* public Graph load(Key key) throws AnyException {
* return createExpensiveGraph(key);
* }
* });}
*
*
Or equivalently,
{@code
*
* // In real life this would come from a command-line flag or config file
* String spec = "maximumSize=10000,expireAfterWrite=10m";
*
* LoadingCache graphs = CacheBuilder.from(spec)
* .removalListener(MY_LISTENER)
* .build(
* new CacheLoader() {
* public Graph load(Key key) throws AnyException {
* return createExpensiveGraph(key);
* }
* });}
*
*
The returned cache is implemented as a hash table with similar performance characteristics to
* {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
* {@link Cache} interfaces. The {@code asMap} view (and its collection views) have weakly
* consistent iterators. This means that they are safe for concurrent use, but if other threads
* modify the cache after the iterator is created, it is undefined which of these changes, if any,
* are reflected in that iterator. These iterators never throw {@link
* ConcurrentModificationException}.
*
*
Note: by default, the returned cache uses equality comparisons (the
* {@link Object#equals equals} method) to determine equality for keys or values. However, if
* {@link #weakKeys} was specified, the cache uses identity ({@code ==})
* comparisons instead for keys. Likewise, if {@link #weakValues} or {@link #softValues} was
* specified, the cache uses identity comparisons for values.
*
*
Entries are automatically evicted from the cache when any of
* {@linkplain #maximumSize(long) maximumSize}, {@linkplain #maximumWeight(long) maximumWeight},
* {@linkplain #expireAfterWrite expireAfterWrite},
* {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
* {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are requested.
*
*
If {@linkplain #maximumSize(long) maximumSize} or
* {@linkplain #maximumWeight(long) maximumWeight} is requested entries may be evicted on each cache
* modification.
*
*
If {@linkplain #expireAfterWrite expireAfterWrite} or
* {@linkplain #expireAfterAccess expireAfterAccess} is requested entries may be evicted on each
* cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}. Expired
* entries may be counted by {@link Cache#size}, but will never be visible to read or write
* operations.
*
*
If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or
* {@linkplain #softValues softValues} are requested, it is possible for a key or value present in
* the cache to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be
* removed from the cache on each cache modification, on occasional cache accesses, or on calls to
* {@link Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be
* visible to read or write operations.
*
*
Certain cache configurations will result in the accrual of periodic maintenance tasks which
* will be performed during write operations, or during occasional read operations in the absence of
* writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
* calling it should not be necessary with a high throughput cache. Only caches built with
* {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
* {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
* {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic
* maintenance.
*
*
The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
* retain all the configuration properties of the original cache. Note that the serialized form does
* not include cache contents, but only configuration.
*
*
See the Guava User Guide article on caching for a higher-level
* explanation.
*
* @param the base key type for all caches created by this builder
* @param the base value type for all caches created by this builder
* @author Charles Fry
* @author Kevin Bourrillion
* @since 10.0
*/
public final class CacheBuilder {
public static final Ticker NULL_TICKER = new Ticker() {
@Override
public long read() {
return 0;
}
};
static final int UNSET_INT = -1;
static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
static final int DEFAULT_EXPIRATION_NANOS = 0;
static final int DEFAULT_REFRESH_NANOS = 0;
private final int initialCapacity = UNSET_INT;
private final int concurrencyLevel = UNSET_INT;
private long maximumSize = UNSET_INT;
private final long maximumWeight = UNSET_INT;
private final long expireAfterWriteNanos = UNSET_INT;
private long expireAfterAccessNanos = UNSET_INT;
private final long refreshNanos = UNSET_INT;
// TODO(fry): make constructor private and update tests to use newBuilder
private CacheBuilder() {
}
/**
* Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
* strong values, and no automatic eviction of any kind.
*/
public static CacheBuilder