3
Good evening, everyone,
See the following code:
Controller
@WebServlet("/testConcurrency")
public class TestConcurrency extends HttpServlet {
    private static final long serialVersionUID = -6124392524678396101L;
    @EJB(name="bs/UsuarioBS/local")
    private UsuarioBSLocal usuarioBS;
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String emailStr = request.getParameter("email");
        System.out.println("[Inicio] usuarioBS.testConcurrency();");
        try {
            usuarioBS.testConcurrency(emailStr);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        System.out.println("[Fim] usuarioBS.testConcurrency();");
    }
}
BS
@Stateless(name="business/UsuarioBS")
public class UsuarioBS implements UsuarioBSLocal {
    private Logger log = Logger.getLogger(UsuarioBS.class);
    @EJB(name="dao/EmailDAO/local")
    private EmailDAOLocal emailDAO;
    @Override
    public void testConcurrency(String emailStr) throws BusinessException {
        try {
            boolean existeEmail = emailDAO.existeEmail(emailStr);
            System.out.println("Existe email ["+ emailStr +"]? " + existeEmail);
            if (!existeEmail) {
                Email email = new Email(emailStr);
                email.setPessoa(new Pessoa(1l));
                email.setTipoEmail(TipoEmail.PRINCIPAL);
                try {
                    System.out.println("Waiting...");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                emailDAO.inserir(email);
                System.out.println("Email ["+ emailStr +"] inserido!");
            }
        } catch (DAOException e) {
            e.printStackTrace();
        }
    }
}
If I call the /testConcurrent url twice? [email protected] in less than 5 seconds it will insert the email twice, which cannot occur.
Ps: Thread.Sleep() is only to illustrate the problem. Elsewhere in my application I also call the emailDAO.existeEmail method().
How can I fix this?
Thank you very much.
Thread.Sleep() was inserted only to illustrate the problem. Here I am using JDBC. I’ve read about transaction attributes, but honestly I didn’t understand it very well. How it would be implemented in practice based on this code?
– user4919