[id='expiration_example-{context}']
= Expiration Examples
When you configure {brandname} to expire entries, you can set lifespan and
maximum idle times for:

* All entries in a cache (cache-wide). You declaratively configure cache-wide expiration in `infinispan.xml` or programmatically using the `ConfigurationBuilder`.
* Per entry, which takes priority over cache-wide expiration values. You configure expiration for specific entries when you create them.

[NOTE]
====
When you explicitly define lifespan and maximum idle time values for cache
entries, {brandname} replicates those values across the cluster along with the
cache entries. Likewise, {brandname} persists expiration values along with the
entries if you configure cache stores.
====

.Configuring expiration for all cache entries

Expire all cache entries after 2 seconds:

[source,xml,options="nowrap",subs=attributes+]
----
<expiration lifespan="2000" />
----

Expire all cache entries 1 second after last access time:

[source,xml,options="nowrap",subs=attributes+]
----
<expiration max-idle="1000" />
----

Disable the expiration reaper with the `interval` attribute and manually expire
entries 1 second after last access time:

[source,xml,options="nowrap",subs=attributes+]
----
<expiration max-idle="1000" interval="-1" />
----

Expire all cache entries after 5 seconds or 1 second after the last access
time, whichever happens first:

[source,xml,options="nowrap",subs=attributes+]
----
<expiration lifespan="5000" max-idle="1000" />
----

.Configuring expiration when creating cache entries

The following example shows how to configure lifespan and maximum idle values
when creating cache entries:

[source,java]
----
// Use cache-wide expiration configuration.
cache.put("pinot noir", pinotNoirPrice); <1>

// Define a lifespan value of 2.
cache.put("chardonnay", chardonnayPrice, 2, TimeUnit.SECONDS); <2>

// Define a lifespan value of -1 (disabled) and a max-idle value of 1.
cache.put("pinot grigio", pinotGrigioPrice,
          -1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); <3>

// Define a lifespan value of 5 and a max-idle value of 1.
cache.put("riesling", rieslingPrice,
          5, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); <4>
----

In a scenario where `infinispan.xml` defines a lifespan value of `1000` for all entries, the preceding `Cache.put()` requests cause the entries to expire:

<1> After 1 second.
<2> After 2 seconds.
<3> 1 second after last access time.
<4> After 5 seconds or 1 second after the last access time, whichever happens first.

.Reference

* link:{configdocroot}[{brandname} Configuration Schema]
* link:{javadocroot}/org/infinispan/configuration/cache/ExpirationConfigurationBuilder.html[org.infinispan.configuration.cache.ExpirationConfigurationBuilder]
* link:{javadocroot}/org/infinispan/expiration/ExpirationManager.html[org.infinispan.expiration.ExpirationManager]
