I am developing webapp using Spring MVC and have a such methods in my application:
@Transactional
public void methodA(Long id, String color) {
Fruit fruit = entityManager.createNamedQuery("Fruit.findById", Fruit.class).setParameter(1, id).getSingleResult();
fruit.setColor("color");
entityManager.merge(fruit);
}
@Transactional
public void methodB(Long id, int price) {
Fruit fruit = entityManager.createNamedQuery("Fruit.findById", Fruit.class).setParameter(1, id).getSingleResult();
fruit.setPrice(price);
entityManager.merge(fruit);
}
This two methods are often called almost at the same time, and because of that a race condition occurs. Is there a way to fix this problem? I think putting both of them in one synchronized method wouldn't be a good idea, because I expect a lot of calls of these methods (thousands) by different users at the same time, so it can cause delays. Fix me if I am wrong.