org.feijoas.mango.common.cache

CacheBuilder

Related Docs: object CacheBuilder | package cache

final case class CacheBuilder[-K, -V] extends Product with Serializable

A builder of LoadingCache and Cache instances having any combination of the following features:

These features are all optional; caches can be created using all or none of them. By default cache instances created by CacheBuilder will not perform any type of eviction.

Usage example:

val createExpensiveGraph: Key => Graph = ...

val graphs: LoadingCache[Key, Graph] = CacheBuilder.newBuilder()
    .maximumSize(10000)
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .removalListener(MY_LISTENER)
    .build(createExpensiveGraph)

This class just delegates to the CacheBuilder implementation in Guava

Note: by default, the returned cache uses equality comparisons to determine equality for keys or values. However, if weakKeys was specified, the cache uses identity (eq) comparisons instead for keys. Likewise, if weakValues or softValues was specified, the cache uses identity comparisons for values.

Entries are automatically evicted from the cache when any of

are requested.

If maximumSize or maximumWeight is requested entries may be evicted on each cache modification.

If expireAfterWrite or #expireAfterAccess is requested entries may be evicted on each cache modification, on occasional cache accesses, or on calls to Cache.cleanUp(). Expired entries may be counted in Cache.size()}, but will never be visible to read or write operations.

If weakKeys, weakValues, or 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 Cache.cleanUp(); such entries may be counted in 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 absense of writes. The 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 removalListener, expireAfterWrite, expireAfterAccess, weakKeys, weakValues, or softValues perform periodic maintenance.

The caches produced by 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.

Warning: This implementation differs from Guava. It is truly immutable and returns a new instance on each method call. Use the standard method-chaining idiom, as illustrated in the documentation above. This has the advantage that it is not possible to create a cache whose key or value type is incompatible with e.g. the weigher. This CacheBuilder is also contravariant in both type K and V.

See the Guava User Guide for more information.

K

the key of the cache

V

the value of the cache

Since

0.7 (copied from Guava-libraries)

Linear Supertypes
Serializable, Serializable, Product, Equals, AnyRef, Any
Ordering
  1. Alphabetic
  2. By inheritance
Inherited
  1. CacheBuilder
  2. Serializable
  3. Serializable
  4. Product
  5. Equals
  6. AnyRef
  7. Any
  1. Hide All
  2. Show all
Learn more about member selection
Visibility
  1. Public
  2. All

Value Members

  1. final def !=(arg0: Any): Boolean

    Definition Classes
    AnyRef → Any
  2. final def ##(): Int

    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean

    Definition Classes
    AnyRef → Any
  4. final def asInstanceOf[T0]: T0

    Definition Classes
    Any
  5. def build[K1 <: K, V1 <: V](loader: CacheLoader[K1, V1]): LoadingCache[K1, V1]

    Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied CacheLoader.

    Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied CacheLoader. If another thread is currently loading the value for this key, simply waits for that thread to finish and returns its loaded value. Note that multiple threads can concurrently load values for distinct keys.

    This method does not alter the state of this CacheBuilder instance, so it can be invoked again to create multiple independent caches.

    loader

    the cache loader used to obtain new values

    returns

    a cache having the requested features

  6. def build[K1 <: K, V1 <: V](loader: (K1) ⇒ V1): LoadingCache[K1, V1]

    Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied loader (the function used to compute corresponding values).

    Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied loader (the function used to compute corresponding values). If another thread is currently loading the value for this key, simply waits for that thread to finish and returns its loaded value. Note that multiple threads can concurrently load values for distinct keys.

    This method does not alter the state of this CacheBuilder instance, so it can be invoked again to create multiple independent caches.

    loader

    the cache loader used to obtain new values

    returns

    a cache having the requested features

  7. def build[K1 <: K, V1 <: V](): Cache[K1, V1]

    Builds a cache which does not automatically load values when keys are requested.

    Builds a cache which does not automatically load values when keys are requested.

    Consider build(CacheLoader) instead, if it is feasible to implement a CacheLoader.

    This method does not alter the state of this CacheBuilder instance, so it can be invoked again to create multiple independent caches.

    returns

    a cache having the requested features

  8. def clone(): AnyRef

    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  9. def concurrencyLevel(concurrencyLevel: Int): CacheBuilder[K, V]

    Guides the allowed concurrency among update operations.

    Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention. Because assignment of entries to these partitions is not necessarily uniform, the actual concurrency observed may vary. Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention. But overestimates and underestimates within an order of magnitude do not usually have much noticeable impact. A value of one permits only one thread to modify the cache at a time, but since read operations and cache loading computations can proceed concurrently, this still yields higher concurrency than full synchronization.

    Defaults to 4. Note: The default may change in the future. If you care about this value, you should always choose it explicitly.

    The current implementation uses the concurrency level to create a fixed number of hashtable segments, each governed by its own write lock. The segment lock is taken once for each explicit write, and twice for each cache loading computation (once prior to loading the new value, and once after loading completes). Much internal cache management is performed at the segment granularity. For example, access queues and write queues are kept per segment when they are required by the selected eviction algorithm. As such, when writing unit tests it is not uncommon to specify concurrencyLevel(1) in order to achieve more deterministic eviction behavior.

    Note that future implementations may abandon segment locking in favor of more advanced concurrency controls.

    Exceptions thrown

    IllegalArgumentException if concurrencyLevel is nonpositive

  10. final def eq(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  11. def expireAfterAccess(duration: Long, unit: TimeUnit): CacheBuilder[K, V]

    Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access.

    Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access. Access time is reset by all cache read and write operations.

    When duration is zero, this method hands off to maximumSize(Long) (0), ignoring any otherwise-specificed maximum size or weight. This can be useful in testing, or to disable caching temporarily without a code change.

    Expired entries may be counted in Cache.size(), but will never be visible to read or write operations. Expired entries are cleaned up as part of the routine maintenance described in the class doc.

    duration

    the length of time after an entry is last accessed that it should be automatically removed

    unit

    the unit that duration is expressed in

    Exceptions thrown

    IllegalArgumentException if duration is negative

  12. def expireAfterWrite(duration: Long, unit: TimeUnit): CacheBuilder[K, V]

    Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

    Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

    When duration is zero, this method hands off to maximumSize(Long) (0), ignoring any otherwise-specificed maximum size or weight. This can be useful in testing, or to disable caching temporarily without a code change.

    Expired entries may be counted in Cache#size, but will never be visible to read or write operations. Expired entries are cleaned up as part of the routine maintenance described in the class doc.

    duration

    the length of time after an entry is created that it should be automatically removed

    unit

    the unit that duration is expressed in

    Exceptions thrown

    IllegalArgumentException if duration is negative

  13. def finalize(): Unit

    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  14. final def getClass(): Class[_]

    Definition Classes
    AnyRef → Any
  15. def initialCapacity(initialCapacity: Int): CacheBuilder[K, V]

    Sets the minimum total size for the internal hash tables.

    Sets the minimum total size for the internal hash tables. For example, if the initial capacity is 60, and the concurrency level is 8, then eight segments are created, each having a hash table of size eight. Providing a large enough estimate at construction time avoids the need for expensive resizing operations later, but setting this value unnecessarily high wastes memory.

    Exceptions thrown

    IllegalArgumentException if initialCapacity is negative

  16. final def isInstanceOf[T0]: Boolean

    Definition Classes
    Any
  17. def maximumSize(size: Long): CacheBuilder[K, V]

    Specifies the maximum number of entries the cache may contain.

    Specifies the maximum number of entries the cache may contain. Note that the cache may evict an entry before this limit is exceeded. As the cache size grows close to the maximum, the cache evicts entries that are less likely to be used again. For example, the cache may evict an entry because it hasn't been used recently or very often.

    When size is zero, elements will be evicted immediately after being loaded into the cache. This can be useful in testing, or to disable caching temporarily without a code change.

    This feature cannot be used in conjunction with maximumWeight.

    size

    the maximum size of the cache

    Exceptions thrown

    IllegalArgumentException if size is negative

  18. def maximumWeight(weight: Long): CacheBuilder[K, V]

    Specifies the maximum weight of entries the cache may contain.

    Specifies the maximum weight of entries the cache may contain. Weight is determined using the weigher specified with weigher((K1, V1) => Int), and use of this method requires a corresponding call to weigher prior to calling build.

    Note that the cache may evict an entry before this limit is exceeded. As the cache size grows close to the maximum, the cache evicts entries that are less likely to be used again. For example, the cache may evict an entry because it hasn't been used recently or very often.

    When weight is zero, elements will be evicted immediately after being loaded into cache. This can be useful in testing, or to disable caching temporarily without a code change.

    Note that weight is only used to determine whether the cache is over capacity; it has no effect on selecting which entry should be evicted next.

    This feature cannot be used in conjunction with maximumSize.

    weight

    the maximum total weight of entries the cache may contain

    Exceptions thrown

    IllegalArgumentException if weight is negative

  19. final def ne(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  20. final def notify(): Unit

    Definition Classes
    AnyRef
  21. final def notifyAll(): Unit

    Definition Classes
    AnyRef
  22. def recordStats(): CacheBuilder[K, V]

    Enable the accumulation of CacheStats during the operation of the cache.

    Enable the accumulation of CacheStats during the operation of the cache. Without this Cache.stats() will return zero for all statistics. Note that recording stats requires bookkeeping to be performed with each operation, and thus imposes a performance penalty on cache operation.

  23. def refreshAfterWrite(duration: Long, unit: TimeUnit): CacheBuilder[K, V]

    Specifies that active entries are eligible for automatic refresh once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

    Specifies that active entries are eligible for automatic refresh once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value. The semantics of refreshes are specified in LoadingCache.refresh(), and are performed by calling CacheLoader.reload().

    As the default implementation of CacheLoader.reload() is synchronous, it is recommended that users of this method override CacheLoader.reload() with an asynchronous implementation; otherwise refreshes will be performed during unrelated cache read and write operations.

    Currently automatic refreshes are performed when the first stale request for an entry occurs. The request triggering refresh will make a blocking call to CacheLoader.reload() and immediately return the new value if the returned future is complete, and the old value otherwise.

    Note: all exceptions thrown during refresh will be logged and then swallowed.

    duration

    the length of time after an entry is created that it should be considered stale, and thus eligible for refresh

    unit

    the unit that duration is expressed in

    Exceptions thrown

    IllegalArgumentException if duration is negative

  24. def removalListener[K1 <: K, V1 <: V](listener: (RemovalNotification[K1, V1]) ⇒ Unit): CacheBuilder[K1, V1]

    Specifies a listener instance that caches should notify each time an entry is removed for any RemovalCause reason.

    Specifies a listener instance that caches should notify each time an entry is removed for any RemovalCause reason. Each cache created by this builder will invoke this listener as part of the routine maintenance described in the class documentation above.

    Warning: any exception thrown by listener will not be propagated to the Cache user, only logged via a Logger.

    returns

    the cache builder reference that should be used instead of this for any remaining configuration and cache building

  25. def softValues(): CacheBuilder[K, V]

    Specifies that each value (not key) stored in the cache should be wrapped in a SoftReference (by default, strong references are used).

    Specifies that each value (not key) stored in the cache should be wrapped in a SoftReference (by default, strong references are used). Softly-referenced objects will be garbage-collected in a globally least-recently-used manner, in response to memory demand.

    Warning: in most circumstances it is better to set a per-cache #maximumSize(long) maximum size instead of using soft references. You should only use this method if you are well familiar with the practical consequences of soft references.

    Note: when this method is used, the resulting cache will use identity (eq) comparison to determine equality of values.

    Entries with values that have been garbage collected may be counted in Cache.size(), but will never be visible to read or write operations; such entries are cleaned up as part of the routine maintenance described in the class doc.

  26. final def synchronized[T0](arg0: ⇒ T0): T0

    Definition Classes
    AnyRef
  27. def ticker(ticker: Ticker): CacheBuilder[K, V]

    Specifies a nanosecond-precision time source for use in determining when entries should be expired.

    Specifies a nanosecond-precision time source for use in determining when entries should be expired. By default, System#nanoTime is used.

    The primary intent of this method is to facilitate testing of caches which have been configured with expireAfterWrite or expireAfterAccess.

    Exceptions thrown

    IllegalStateException if a ticker was already set

  28. final def wait(): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  29. final def wait(arg0: Long, arg1: Int): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  30. final def wait(arg0: Long): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  31. def weakKeys(): CacheBuilder[K, V]

    Specifies that each key (not value) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

    Specifies that each key (not value) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

    Warning: when this method is used, the resulting cache will use identity (eq) comparison to determine equality of keys.

    Entries with keys that have been garbage collected may be counted in Cache.size(), but will never be visible to read or write operations; such entries are cleaned up as part of the routine maintenance described in the class doc.

    Exceptions thrown

    IllegalStateException if the key strength was already set

  32. def weakValues(): CacheBuilder[K, V]

    Specifies that each value (not key) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

    Specifies that each value (not key) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

    Weak values will be garbage collected once they are weakly reachable. This makes them a poor candidate for caching; consider #softValues instead.

    Note: when this method is used, the resulting cache will use identity (eq) comparison to determine equality of values.

    Entries with values that have been garbage collected may be counted in Cache#size, but will never be visible to read or write operations; such entries are cleaned up as part of the routine maintenance described in the class doc.

  33. def weigher[K1 <: K, V1 <: V](weigher: (K1, V1) ⇒ Int): CacheBuilder[K1, V1]

    Specifies the weigher to use in determining the weight of entries.

    Specifies the weigher to use in determining the weight of entries. Entry weight is taken into consideration by maximumWeight(Long) when determining which entries to evict, and use of this method requires a corresponding call to maximumWeight(Long) prior to calling build. Weights are measured and recorded when entries are inserted into the cache, and are thus effectively static during the lifetime of a cache entry.

    When the weight of an entry is zero it will not be considered for size-based eviction (though it still may be evicted by other means).

    weigher

    the weigher to use in calculating the weight of cache entries

Inherited from Serializable

Inherited from Serializable

Inherited from Product

Inherited from Equals

Inherited from AnyRef

Inherited from Any

Ungrouped