Invalidation Mode with Embedded Infinispan

What You Will Learn

How to configure an Infinispan cluster in invalidation mode, where nodes do not share data but instead invalidate stale entries across the cluster when data is added, updated, or removed.

Prerequisites

  • Java 17+

Step 1: Add the Embedded Dependency

Add Infinispan core to your pom.xml:

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-core</artifactId>
</dependency>

Step 2: Configure Invalidation Mode

Create a clustered cache manager and define a cache with INVALIDATION_SYNC mode:

      // Create a clustered configuration and a default cache named test
      GlobalConfiguration global = GlobalConfigurationBuilder.defaultClusteredBuilder().build();

      // Create the cache manager
      cacheManager = new DefaultCacheManager(global);

      // Clustered mode invalidation sync. Can also be async
      Configuration config = new ConfigurationBuilder()
              .clustering().cacheMode(CacheMode.INVALIDATION_SYNC)
              .build();

      // Define a cache configuration
      cacheManager.defineConfiguration("test", config);

      // Retrieve the cache
      cache = cacheManager.getCache("test");

In this mode, when a value is added or updated on one node, the corresponding entry is invalidated (removed) on all other nodes.

Step 3: Use Put and PutForExternalRead

A standard put invalidates matching entries on other nodes:

      // Will put the key/value pair and invalidate the key/value pair that may exist in other nodes
      cache.put(key, value);

Use putForExternalRead to store a value locally without triggering invalidation on other nodes. This is useful when loading data from an external source:

      //Put for external read won't invalidate the value if it's present in another node.
      cache.putForExternalRead(key, value);

Note that putForExternalRead may result in stale data if the same key exists with a different value on another node.

Step 4: Run the Tutorial

Run the tutorial in two or more separate terminals to form a cluster:

mvn package exec:java

An interactive menu lets you put, get, and remove entries. Observe how a put on one node invalidates the entry on the other, while putForExternalRead does not.

What’s Next