Cache Sizing and Expiry
Solve the two invalidation problems that make a cache usable in production: bound the on-heap tier with LRU eviction, set entry lifetime with JCache expiry policies, and watch the cache manage itself.
Introduction
"There are only two hard things in computer science: cache invalidation and naming things" (attributed to Phil Karlton, a principal engineer at Netscape in the 1990s). This tutorial takes on the first one.
You can put and get data with IgniteCache after Work with the Cache API. That is enough to call it a cache, but two problems make an unbounded cache unusable in production.
Without a size ceiling, every put expands the memory footprint until the JVM or the server's off-heap region runs out. A cache with no entry expiry is worse. It keeps serving data that has already gone stale in the source system. Neither is a bug that surfaces in a 1,000-entry test. Both are real under production load.
This tutorial solves both. You add on-heap LRU eviction to bound the JVM-heap footprint, set TTL with a JCache ExpiryPolicy to control freshness, and watch a real-time snapshot of the cache shrinking itself as entries leave under both rules. By the end, you have the vocabulary and code patterns the next tutorial needs when it connects the cache to a MariaDB database and leans on expiry semantics to keep cache-aside coherent.
One distinction sets up everything that follows. A cache is not a ConcurrentMap. A ConcurrentMap grows forever and holds data until the application explicitly removes it. A cache is a bounded, ephemeral view over data that actively manages what it keeps. Eviction and expiry are not features bolted onto a Map. They separate a cache from a map that happens to live in memory.
This tutorial labels itself "beginner" for GridGain. The surrounding Java stack (Maven, JDBC, Spring XML) is assumed prior knowledge. If any of those is new, skim the linked primer before starting.
Prerequisites
A running single-node cluster from Start a Local Cache Development Cluster
Java 17 or later
Maven 3.6 or later
JCache
ExpiryPolicyterminology will be introduced; no prior knowledge assumed.
What You Will Learn
You build four small programs that progress from a naive unbounded cache to a self-managing cache. Each program reveals one mechanism.
Write an unbounded cache and see why it is a memory leak
Bound the on-heap tier with
LruEvictionPolicyFactory, and understand why that does not bound the off-heap storeSet entry lifetime with JCache
CreatedExpiryPolicy, and choose between the four policy variantsWatch a two-tier snapshot loop as the cache shrinks itself under combined eviction and expiry rules
Set up the Maven Project
Create a project directory alongside your cache-cluster directory and add a pom.xml:
Create cache-client/pom.xml:
GridGain 8 artifacts are published to GridGain's Nexus repository, not Maven Central. The <repositories> block tells Maven where to find the gridgain-core dependency.
This pom.xml matches the one from Work with the Cache API. If you kept that project, you can continue using it; the four classes in this tutorial live in the same com.example package and the same exec-maven-plugin invocation runs them. The exec.mainClass property in <properties> is overridden on each mvn exec:exec call, so you switch between classes without editing the pom.
Observe the Unbounded Cache Problem
Start with the naive case to see what goes wrong. An IgniteCache created with no configuration beyond its name has no size ceiling and no entry lifetime. Every call to put grows the footprint. Nothing ever leaves.
Create cache-client/src/main/java/com/example/UnboundedCache.java:
Run it:
After the GridGain startup output, you see:
One thousand entries in, one thousand entries stored. A cache that keeps everything you write is a slower ConcurrentMap. In production, the loop does not stop at 1,000. It stops when the server runs out of memory. The remaining steps give the cache answers to two questions it cannot answer yet: when should it discard an entry to keep memory bounded, and when does an entry become stale?
Bound the On-Heap Tier With Eviction
Eviction answers one question: when the cache is full, what do I discard? An eviction policy picks an entry at the moment a put would exceed the configured ceiling. LRU (least recently used) is the default choice for caching workloads because recency predicts future access. GridGain ships FIFO and sorted policies as well, but LRU is the right starting point unless the access pattern gives you a better signal.
One piece of mental model before the code. GridGain stores cache data primarily off-heap, outside the JVM heap. The off-heap store avoids garbage-collection pressure and lets a single JVM hold many gigabytes of cached data. The on-heap tier is an optional bounded overlay for hot entries, and policy-based eviction operates on that overlay. Opt in with setOnheapCacheEnabled(true). Without it, the cluster rejects the cache configuration with IgniteCheckedException: Onheap cache must be enabled if eviction policy is configured.
LRU therefore caps the on-heap tier, not the total cached data. That maps to what most production deployments need: a bound on the JVM heap footprint per cache. Bounding the off-heap region is a data-region configuration covered in a later tutorial.
Create cache-client/src/main/java/com/example/BoundedCache.java:
Run it:
Three distinct counts tell the story. cache.size() without arguments reports 1,000 across all tiers because every entry still lives somewhere. The ONHEAP peek mode returns 100, exactly the setMaxSize ceiling on the bounded hot tier. The OFFHEAP peek mode returns 1,000 from the primary store, unaffected by the on-heap policy.
A few details to note:
LruEvictionPolicyFactoryis the current idiom. The oldersetEvictionPolicy(new LruEvictionPolicy(100))setter is@Deprecatedin favor of the factory form.Eviction is lazy. LRU discards an entry only when a put would exceed the bound, not on a continuous background pass. The on-heap count sits at exactly 100 for the same reason: the policy keeps demoting one older entry per new put.
Other eviction policies exist. GridGain 8 ships
FifoEvictionPolicyFactory(discard the oldest insertion) andSortedEvictionPolicyFactory(discard by a custom comparator). LRU is the right starting point for most caching workloads; pick one of the others when your access pattern gives you a better signal than recency.
Set Entry Lifetime With Expiry
Eviction keeps memory bounded. Expiry is about freshness: when does an entry become stale enough to stop trusting? The two controls answer different questions, and a single cache can configure both.
ExpiryPolicy is a JCache (JSR-107) interface. GridGain honors it regardless of whether on-heap caching is enabled or an eviction policy is configured. The four built-in policies anchor lifetime to a different lifecycle event each:
CreatedExpiryPolicy: entries expire N time units after the first put. Subsequent reads and updates do not reset the clock. Use when data has a fixed freshness window, such as an API response cache where the upstream response is only trustworthy for a known interval.ModifiedExpiryPolicy: entries expire N time units after the last put. Use for a catalog with occasional updates: writes mean the value is fresh again.AccessedExpiryPolicy: entries expire N time units after the last read. Use for a session cache where hot sessions should stay and cold ones should drop.TouchedExpiryPolicy: entries expire N time units after either a read or a write. Use when both access patterns should keep an entry alive.
This step uses CreatedExpiryPolicy. The others share the same setter and the same factory pattern.
Create cache-client/src/main/java/com/example/ExpiringCache.java:
Run it:
The count drops to zero with no application call to remove anything. Expiry fires eagerly. Each server node runs a background worker (ttl-cleanup-worker) every 500ms that scans for expired entries and removes them. The six-second sleep leaves margin for every entry's three-second TTL to elapse and for the sweep to catch them. A shorter sleep can still show a few entries, because the sweep does not run at the exact moment an entry expires.
Three follow-on details worth surfacing:
setEagerTtl(true)is explicit for visibility, not for correctness. Both products default to true. A production operator who wants lazy expiry (lower sweep CPU cost, at the price of expired entries occupying memory until a later read) sets this to false.Per-operation TTL overrides the cache-wide policy for a single call. Use
cache.withExpiryPolicy(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 1)).create()).put(key, value)when one entry needs a different lifetime from the rest. The returned view shares the underlying cache; only that operation's entry lifetime changes.Expiry removes from every tier. Unlike on-heap eviction, which demotes an entry out of the hot tier while leaving it in off-heap, expiry removes the entry from on-heap and off-heap together. That is why
cache.size()drops to zero and stays there.
Watch the Cache Manage Itself
So far each control has been visible through a single before-and-after count. A production cache manages itself continuously, not at snapshot boundaries. This final program combines both controls, loads entries just over the on-heap cap, and prints a real-time snapshot of both tiers every 500 milliseconds so you watch the cache shrink as it runs.
Configuration in this step:
On-heap cap: 20 (smaller than Step 3 so the evicted count is visible against the 30-entry load)
TTL: 2 seconds (short enough that the snapshot loop captures the decay)
30 entries loaded (overflows the on-heap cap by 10, leaves room for the TTL sweep)
Create cache-client/src/main/java/com/example/ManagedCache.java:
Run it:
Read the snapshot top to bottom. At t+0.0s, the load just finished: on-heap is capped at 20 (LRU pushed entries 0 through 9 out of the hot tier as entries 20 through 29 came in), off-heap holds all 30. For the first two seconds nothing changes, because neither rule has triggered yet. At t+2.1s the server's TTL sweep has caught five expired entries and dropped them from both tiers. By t+2.7s, the remaining entries have expired and the cache is empty. The whole show took under three seconds and did not involve a single application-level remove.
A few things are worth noticing:
On-heap at 20 during the load means LRU worked during the puts, not after. The policy fires inline with each put that would otherwise exceed the cap, demoting the least recently used on-heap entry. Off-heap still holds the demoted entry.
Off-heap drops in batches, not one-by-one. The TTL sweep processes up to 1,000 expired entries per cache per pass. The 30 → 25 → 0 pattern reflects sweep timing, not a per-entry delay.
The time column exposes the cadence. Production monitoring that tracks cache size over time shows the same shape: the on-heap count flatlines at the LRU cap while writes are arriving, then both tiers decay once traffic subsides and TTL catches up.
Summary
A cache is not a ConcurrentMap. It actively manages its contents under rules the application configures once and never touches again. You built four programs that make those rules visible:
UnboundedCacheheld every entry you wrote, which named the problem the rest of the tutorial solves.BoundedCachebounded the on-heap tier withLruEvictionPolicyFactoryand surfaced GridGain's two-tier storage model. LRU caps the JVM-heap footprint per cache. Bounding the off-heap region itself is a data-region configuration covered in a later tutorial.ExpiringCacheset a three-second entry lifetime withCreatedExpiryPolicy. The other three JCache policies cover update-based, access-based, and touched-based freshness windows.ManagedCachecombined both controls and watched the cache discard entries on its own. The two-tier snapshot loop is a diagnostic; production applications usually subscribe to invalidation events through JCache listeners or GridGain continuous queries.
Those four programs map to the two failure modes of a naive cache. Eviction is the answer to unbounded memory growth: LRU discards the least recently used on-heap entry whenever a put would exceed the cap. Expiry is the answer to stale data, with four JCache policies that anchor entry lifetime to creation, modification, access, or either. Configured together, the two controls turn a distributed ConcurrentMap into something that behaves like a cache under real workloads.
Next Step
The next tutorial adds a database. Cache-aside reads the cache first, falls through to MariaDB on a miss, and populates the cache with the fresh row. Cache-aside has no answer for stale data on its own. The expiry semantics you just set are what keep the pattern coherent over time.
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

