Basic Transaction Example
This example operates on two replicated regions. It begins a transaction, updates one entry in each region, and commits the result.
If the commit fails, it will be due to a CommitConflictException
, which implies that a concurrent access caused a change to one of the items operated on within this transaction. This code fragment catches the exception, and it repeats the transaction attempt until the commit succeeds.
Cache c = new CacheFactory().create();
Region<String, Integer> cash = c.createRegionFactory<String, Integer>()
.setDataPolicy(DataPolicy.REPLICATE)
.create("cash");
Region<String, Integer> trades = c.createRegionFactory<String, Integer>()
.setDataPolicy(DataPolicy.REPLICATE)
.create("trades");
CacheTransactionManager txmgr = c.getCacheTransactionManager();
boolean commitConflict = false;
do {
try {
txmgr.begin();
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);
txmgr.commit();
commitConflict = false;
}
catch (CommitConflictException conflict) {
commitConflict = true;
}
} while (commitConflict);