Pivotal GemFire® v8.2

Basic Transaction Example

Basic Transaction Example

This example begins a transaction, updates two replicated regions, cash and trades, and commits.

If the commit fails, it throws a CommitConflictException and the transaction is rolled back. In this example, this type of exception could only occur if there was concurrent access to the same key and value inside another transaction.

Cache c = new CacheFactory().create();

Region<String, Integer> cash = c.createRegionFactory<String, Integer>()

Region<String, Integer> trades = c.createRegionFactory<String, Integer>()

CacheTransactionManager txmgr = c.getCacheTransactionManager();
try {
	final String customer = "Customer1";
	final Integer purchase = Integer.valueOf(1000);
// Decrement cash
	Integer cashBalance = cash.get(customer);
	Integer newBalance = 
		Integer.valueOf((cashBalance != null ? cashBalance : 0) 
			- purchase);
	cash.put(customer, newBalance);
// Increment trades
	Integer tradeBalance = trades.get(customer);
	newBalance = 
		Integer.valueOf((tradeBalance != null ? tradeBalance : 0) 
			+ purchase);

	trades.put(customer, newBalance);
catch (CommitConflictException conflict)