---
title:  Basic Transaction Example
---

<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

This example operates on two replicated regions. It begins a transaction, updates one entry in each region, and commits the result.

<a id="concept_F8D96C21C8444F99B47909CDEB86E60A__section_B6818C348224456387DEC5C9D3B5F250"></a>
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.

``` pre
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);
```


