トランザクション分離の Java の例
トランザクション分離 は、1 つの操作で行われた変更がどのように他の並行操作に可視に なるのかを定義します。 以下の例を使用して、Java™ アプリケーションでトランザクション分離レベルを定義できます。
ペシミスティック・ロックでの反復可能読み取り
map = session.getMap("Order");
session.setTransactionIsolation(Session.TRANSACTION_REPEATABLE_READ);
session.begin();
// An S lock is requested and held and the value is copied into
// the transactional cache.
Order order = (Order) map.get("100");
// The entry is evicted from the transactional cache.
map.invalidate("100", false);
// The same value is requested again. It already holds the
// lock, so the same value is retrieved and copied into the
// transactional cache.
Order order2 = (Order) map.get("100");
// All locks are released after the transaction is synchronized
// with cache map.
session.commit();幻償読み取り
session1.setTransactionIsolation(Session.TRANSACTION_REPEATABLE_READ);
session1.begin();
// A query is run which selects a range of values.
ObjectQuery query = session1.createObjectQuery
("SELECT o FROM Order o WHERE o.itemName='Widget'");
// In this case, only one order matches the query filter.
// The order has a key of "100".
// The query engine automatically acquires an S lock for Order "100".
Iterator result = query.getResultIterator();
// A second transaction inserts an order that also matches the query.
Map orderMap = session2.getMap("Order");
orderMap.insert("101", new Order("101", "Widget"));
// When the query runs again in the current transaction, the
// new order is visible and will return both Orders "100" and "101".
result = query.getResultIterator();
// All locks are released after the transaction is synchronized
// with cache map.
session.commit();ペシミスティック・ロックでの読み取りコミット済み
map1 = session1.getMap("Order");
session1.setTransactionIsolation(Session.TRANSACTION_READ_COMMITTED);
session1.begin();
// An S lock is requested but immediately released and
//the value is copied into the transactional cache.
Order order = (Order) map1.get("100");
// The entry is evicted from the transactional cache.
map1.invalidate("100", false);
// A second transaction updates the same order.
// It acquires a U lock, updates the value, and commits.
// The ObjectGrid successfully acquires the X lock during
// commit since the first transaction is using read
// committed isolation.
Map orderMap2 = session2.getMap("Order");
session2.begin();
order2 = (Order) orderMap2.getForUpdate("100");
order2.quantity=2;
orderMap2.update("100", order2);
session2.commit();
// The same value is requested again. This time, they
// want to update the value, but it now reflects
// the new value
Order order1Copy = (Order) map1.getForUpdate("100");