Search in sources :

Example 1 with Item

use of org.jpwh.model.concurrency.versiontimestamp.Item in project microservices by pwillhan.

the class VersioningTimestamp method firstCommitWins.

@Test(expectedExceptions = OptimisticLockException.class)
public void firstCommitWins() throws Throwable {
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        Item someItem = new Item();
        someItem.setName("Some Item");
        em.persist(someItem);
        tx.commit();
        em.close();
        final Long ITEM_ID = someItem.getId();
        // Load an item and change its name
        tx.begin();
        em = JPA.createEntityManager();
        Item item = em.find(Item.class, ITEM_ID);
        item.setName("New Name");
        // The concurrent second unit of work doing the same
        Executors.newSingleThreadExecutor().submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                UserTransaction tx = TM.getUserTransaction();
                try {
                    tx.begin();
                    EntityManager em = JPA.createEntityManager();
                    Item item = em.find(Item.class, ITEM_ID);
                    item.setName("Other Name");
                    tx.commit();
                    em.close();
                } catch (Exception ex) {
                    // This shouldn't happen, this commit should win!
                    TM.rollback();
                    throw new RuntimeException("Concurrent operation failure: " + ex, ex);
                }
                return null;
            }
        }).get();
        try {
            tx.commit();
        // Version check: How many rows have been updated?
        } catch (Exception ex) {
            throw unwrapCauseOfType(ex, OptimisticLockException.class);
        }
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.concurrency.versiontimestamp.Item) EntityManager(javax.persistence.EntityManager) OptimisticLockException(javax.persistence.OptimisticLockException) Callable(java.util.concurrent.Callable) OptimisticLockException(javax.persistence.OptimisticLockException) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Aggregations

Callable (java.util.concurrent.Callable)1 EntityManager (javax.persistence.EntityManager)1 OptimisticLockException (javax.persistence.OptimisticLockException)1 UserTransaction (javax.transaction.UserTransaction)1 JPATest (org.jpwh.env.JPATest)1 Item (org.jpwh.model.concurrency.versiontimestamp.Item)1 Test (org.testng.annotations.Test)1