[id='how_eviction_works-{context}']
= How Eviction Works
{brandname} eviction relies on two configurations:

* Size of the data container.
* Eviction strategy.

.Calculating data container size

You configure the maximum size of the data container and specify if {brandname}
stores cache entries as:

* Object in the Java heap.
* Binary `byte[]` in the Java heap.
* Bytes in native memory (off-heap).

|===
| Storage type | Size of the data container is calculated as:

| Object
| Number of entries.

| Binary
| Number of entries, if the eviction type is `COUNT`. +
Amount of memory, in bytes, if the eviction type is `MEMORY`.

| Off-heap
| Number of entries, if the eviction type is `COUNT`. +
Amount of memory, in bytes, if the eviction type is `MEMORY`.
|===

[NOTE]
====
When using `MEMORY`, {brandname} can determine only an approximate size of data
containers, which is optimized for the HotSpot JVM.

When using `MEMORY` with off-heap storage, the calculation is a closer
approximation than on heap.
====

.Evicting cache entries

When an entry is added or modified in the data container, {brandname} compares
the current eviction size to the maximum size. If the current size
exceeds the maximum, {brandname} evicts entries.

Eviction happens immediately in the thread that adds an entry that exceeds the
maximum size.

For example, consider the following configuration:

----
<memory>
  <object size="50" />
</memory>
----

In this case, entries are stored as objects and the data container has a
maximum size of 50 entries.

If 50 entries are in the data container, and a `put()` request attempts to
create a new entry, {brandname} performs eviction.

.Eviction strategies

Strategies control how {brandname} performs eviction. You can either perform eviction manually or configure {brandname} to do one of the following:

* Remove old entries to make space for new ones.
* Throw `ContainerFullException` and prevent new entries from being created.
+
The exception eviction strategy works only with transactional caches that use 2
phase commits; not with 1 phase commits or synchronization optimizations.

[NOTE]
====
{brandname} includes the Caffeine caching library that implements a variation
of the Least Frequently Used (LFU) cache replacement algorithm known as
TinyLFU. For off-heap storage, {brandname} uses a custom implementation of the
Least Recently Used (LRU) algorithm.
====

.References

* link:https://github.com/ben-manes/caffeine[Caffeine]
