Distributed Cache with Embedded Infinispan
What You Will Learn
How to create a clustered Infinispan cache manager in embedded mode, configure a distributed (partitioned) cache, and observe how data is distributed across cluster nodes.
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: Create a Clustered Cache Manager
Use GlobalConfigurationBuilder.defaultClusteredBuilder() to enable JGroups clustering:
public void createDefaultCacheManager() {
// Setup up a clustered cache manager
GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
// Initialize the cache manager
cm1 = new DefaultCacheManager(global.build());
}
This starts a JGroups cluster. Multiple instances on the same network will auto-discover each other.
Step 3: Configure a Distributed Cache
Create a cache with DIST_SYNC mode. In this mode, data is partitioned: each entry is stored on a subset of nodes (by default 2 copies):
public void createAndPopulateTheCache(int size) {
//Create cache configuration
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.DIST_SYNC);
// Create a cache
cache = cm1.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache(DIST_CACHE_NAME, builder.build());
// Store the current node address in some random keys
for (int i = 0; i < size; i++) {
cache.put(UUID.randomUUID().toString(), cm1.getNodeAddress());
}
}
Step 4: Populate and Query the Cache
Store entries and observe ownership. Use Flag.CACHE_MODE_LOCAL to see only entries owned by the local node:
public void displayCacheContent() {
if (cache == null) {
System.out.println("The cache is null");
return;
}
// Display the current cache contents for the whole cluster
cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
// Display the current cache contents for this node
// Note: By default numOwners=2, so in a cluster with 2 nodes, each node owns all the keys:
// some of the keys as "primary owner" and some keys as "backup owner"
cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).entrySet()
.forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
}
Step 5: Run the Tutorial
mvn package exec:java
The local view will show fewer entries than the cluster-wide view because distributed mode partitions data across nodes.
What’s Next
-
Try replicated mode where every node has all data
-
Add cache listeners to react to changes
-
Use distributed streams for parallel processing


