1 Reply Latest reply on Dec 5, 2006 6:08 AM by slad

    Simultaneous access

    slad

      Hi all,

      I am trying to imitate simultaneous access to data, using EJB 3.0 under JBoss 4.0.5GA.
      Stateless session bean has following method:

      @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
       public String fieldInc(int id) {
       EntityManager em = null;
       String result;
      
       try {
       InitialContext ctx = new InitialContext();
       EntityManagerFactory emf = (EntityManagerFactory) ctx.lookup("java:/EntityManagerFactory");
       em = emf.createEntityManager();
       Foo f = em.find(Foo.class, id); // Foo is Entity bean, it represents table in DB under MySQL 5.0.24a
      
       if(f == null) {
       em.close();
       return "No entity found by given id("+id+")";
       }
      
       f.setSomefield(f.getSomefield()+1);
       em.persist(f);
       result = "new field value: "+f.getSomefield();
       em.close();
       return result;
       } catch(Exception e) {
       if(em != null) {
       em.close();
       }
       return e.toString();
       }
       }


      this code is called from servlet like:

      for(int i=0;i<100;i++){
       sess.fieldInc(1);
      }
      


      so, when I start this servlet in 2 windows the field's value doesn't increases by 200, but only ~140. Is that annotation enough to start container managed transaction? Or maybe I should use User Transaction to make concurrent access for modifying data work properly?

      thanks for any advise

        • 1. Re: Simultaneous access
          slad

          okay,

          for(int i=0;i<100;i++){
           synchronized(SimultanServlet.class){
           sess.fieldInc(1);
           }
          }

          helped (don't know if it correct, but it works...)

          the next question is - how to make it work in cluster - synchronized won't help...