Transactions with Embedded Infinispan

What You Will Learn

How to configure a transactional embedded cache and use the JTA TransactionManager to commit and rollback cache operations atomically.

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 a Transactional Cache

Enable transaction mode on the cache configuration:

      // Initialize the cache manager
      cm1 = new DefaultCacheManager();
      // Create a transaction cache config
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
      Configuration cacheConfig = builder.build();
      // Create a cache with the config
      cache = cm1.administration()
              .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
              .getOrCreateCache(CACHE_NAME, cacheConfig);

Step 3: Commit a Transaction

Obtain the TransactionManager and perform operations within a transaction:

      // Obtain the transaction manager
      TransactionManager transactionManager = cache.getAdvancedCache().getTransactionManager();
      // Perform some operations within a transaction and commit it
      transactionManager.begin();
      keyValues.forEach((k, v) -> {
         cache.put(k, v);
      });
      transactionManager.commit();

After the commit, both entries are visible in the cache.

Step 4: Rollback a Transaction

Changes within a rolled-back transaction are discarded:

      // Obtain the transaction manager
      TransactionManager transactionManager = cache.getAdvancedCache().getTransactionManager();
      // Perform some operations within a transaction and commit it
      transactionManager.begin();
      keyValues.forEach((k, v) -> {
         cache.put(k, v);
      });
      transactionManager.rollback();

After the rollback, key1 and key2 still contain their original committed values (value1 and value2).

Step 5: Run the Tutorial

mvn package exec:java

The output shows that after commit, the cache contains the new values, and after rollback, the original values remain unchanged.

What’s Next