0 Replies Latest reply: Mar 21, 2013 9:37 PM by Mr.Sam RSS

    Locking but trx still goes on..

    Mr.Sam
      Hi,

      Here something confusing.

      Used EntityManager lock function in Trx1 and Trx2 at a same time and it did throw PessimisticLockException because javax.persistence.lock.timeout has been set to 0 to make it immediate.

      I found that when the Trx2 try to lock, it will throw exception whereby it is correct.
      The problem is, when the Trx1 is lock and Trx2 did not lock, trx2 still able to update the table without waiting. Both of them are selecting and updateing the same row of data.

      Here my sample code:

      -----
      public String testCase1() {
      List<Itemvend> list;

      try {
      Itemvend itemVend = itemvendFacade.ejbTestCase1();
      } catch (Exception e) {
      e.printStackTrace();
      }

      return "";
      }

      public String testCase2() {
      try {
      Itemvend itemVend = itemvendFacade.ejbTestCase2();

      itemVend.setViBranchCode("00");
      itemvendFacade.edit(itemVend);

      } catch (Exception e) {
      e.printStackTrace();
      }

      return "";
      }
      -----
      I use Thread to delay Trx1 been complete too fast.

      public Itemvend ejbTestCase1() {
      Itemvend itemVend;
      try {
      TypedQuery<Itemvend> userInfo = em.createNamedQuery("Itemvend.findByExtra", Itemvend.class);
      itemVend = userInfo.getSingleResult();

      em.lock(itemVend, LockModeType.PESSIMISTIC_WRITE);

      Thread.sleep(30000);
      return itemVend;
      } catch (Exception e) {
      if(e.toString().contains("javax.persistence.LockTimeoutException")){
      System.out.println("LockTimeoutException");
      return null;
      }else{
      e.printStackTrace();
      return null;
      }
      }
      }

      public Itemvend ejbTestCase2() {
      Itemvend itemVend;
      try {
      TypedQuery<Itemvend> userInfo = em.createNamedQuery("Itemvend.findByExtra", Itemvend.class);
      itemVend = userInfo.getSingleResult();
      return itemVend;
      } catch (Exception e) {
      if(e.toString().contains("javax.persistence.LockTimeoutException")){
      System.out.println("LockTimeoutException");
      return null;
      }else{
      e.printStackTrace();
      return null;
      }
      }
      }

      -----

      While trx1 is in lock state, trx2 should not be able to update due to trx1 is locking it right?

      Is that a way to prevent trx2 to update or select?
      Any ideas?

      Thanks,
      Sam

      Edited by: Mr.Sam on Mar 22, 2013 10:37 AM