Skip to content

Instantly share code, notes, and snippets.

@alanfranz
Last active January 2, 2016 20:39
Show Gist options
  • Save alanfranz/8358322 to your computer and use it in GitHub Desktop.
Save alanfranz/8358322 to your computer and use it in GitHub Desktop.
MapDB transaction overlap
package net.emaze.mavenproject1;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.TxMaker;
import java.util.Map;
import org.junit.Test;
public class TestTransactions {
@Test
public void testSameCollectionInsertDifferentValuesInDifferentTransactions() throws Exception {
TxMaker txMaker = DBMaker
.newMemoryDB()
.makeTxMaker();
DB tx1 = txMaker.makeTx();
DB tx2 = txMaker.makeTx();
Map map1 = tx1.getTreeMap("testMap");
map1.put(1, "asd");
map1.put(2, "asd");
tx1.commit();
System.out.println("tx1 commit succeeded, map size after tx1 commits: " + txMaker.makeTx().getTreeMap("testMap").size());
Map map2 = tx2.getTreeMap("testMap");
map2.put(10000, "somevalue");
// the following line throws a TxRollbackException
tx2.commit();
txMaker.close();
}
@Test
public void testDifferentCollectionsInDifferentTransactions() throws Exception {
TxMaker txMaker = DBMaker
.newMemoryDB()
.makeTxMaker();
DB tx1 = txMaker.makeTx();
DB tx2 = txMaker.makeTx();
Map map1 = tx1.getTreeMap("testMap");
map1.put(1, "asd");
map1.put(2, "asd");
tx1.commit();
System.out.println("tx1 commit succeeded, map size after tx1 commits: " + txMaker.makeTx().getTreeMap("testMap").size());
Map map2 = tx2.getTreeMap("otherMap");
map2.put(20, "somevalue");
// the following line throws a TxRollbackException
tx2.commit();
txMaker.close();
}
@Test
public void testSameCollectionModifyDifferentValuesInDifferentTransactions() throws Exception {
TxMaker txMaker = DBMaker
.newMemoryDB()
.makeTxMaker();
DB txInit = txMaker.makeTx();
txInit.getTreeMap("testMap").put(1, "value1");
txInit.getTreeMap("testMap").put(2, "value2");
txInit.commit();
DB tx1 = txMaker.makeTx();
DB tx2 = txMaker.makeTx();
Map map1 = tx1.getTreeMap("testMap");
map1.put(1, "asd");
tx1.commit();
System.out.println("tx1 commit succeeded, map size after tx1 commits: " + txMaker.makeTx().getTreeMap("testMap").size());
Map map2 = tx2.getTreeMap("testMap");
map2.put(2, "somevalue");
// the following line throws a TxRollbackException
tx2.commit();
txMaker.close();
}
@Test
public void testTransactionsDoingNothing() throws Exception {
TxMaker txMaker = DBMaker
.newMemoryDB()
.makeTxMaker();
DB txInit = txMaker.makeTx();
txInit.getTreeMap("testMap").put(1, "value1");
txInit.getTreeMap("testMap").put(2, "value2");
txInit.commit();
DB tx1 = txMaker.makeTx();
DB tx2 = txMaker.makeTx();
Map map1 = tx1.getTreeMap("testMap");
tx1.commit();
Map map2 = tx2.getTreeMap("testMap");
// the following line throws a TxRollbackException
tx2.commit();
txMaker.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment