Cache Listeners with Embedded Infinispan
What You Will Learn
How to create and register cache listeners in embedded Infinispan to react to entry creation and modification events.
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 Listener Class
Annotate a class with @Listener and define handler methods using event annotations like @CacheEntryCreated and @CacheEntryModified:
@Listener
public static class MyListener {
Map<String, String> created = new HashMap();
Map<String, String> updated = new HashMap<>();
@CacheEntryCreated
public void entryCreated(CacheEntryCreatedEvent<String, String> event) {
// We are only interested in the post event
if (!event.isPre())
created.put(event.getKey(), event.getValue());
System.out.printf("Created %s\n", event.getKey());
}
@CacheEntryModified
public void entryModified(CacheEntryModifiedEvent<String, String> event) {
// We are only interested in the pre event
if (event.isPre())
updated.put(event.getKey(), event.getNewValue());
System.out.printf("About to modify %s\n", event.getKey());
}
}
Each event fires twice — once before (isPre() == true) and once after (isPre() == false) the operation. Filter on the phase you need.
Step 3: Register the Listener
Add the listener to a cache instance:
// Construct a simple local cache manager with default configuration
cacheManager = new DefaultCacheManager();
// Define local cache configuration
cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
// Obtain the local cache
cache = cacheManager.getCache("local");
listener = new MyListener();
// Register a listener
cache.addListener(listener);
Step 4: Trigger Events
Any cache operation triggers the corresponding listener methods:
// Store some values
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key1", "newValue");
Step 5: Run the Tutorial
mvn package exec:java
The output shows creation notifications for key1 and key2, and a modification notification when key1 is updated.
What’s Next
-
Try distributed caching with listeners in a cluster
-
Explore functional map API for lambda-based cache operations
-
Use distributed streams for processing cache data


