Hibernate With Only Optimistic Locking Still Generates Deadlocks

We have a business application which uses Spring Boot, Hibernate, and an underlying Oracle Database (H2 database for tests).
Users make a lot of simultaneous requests to it.

To cope with the many requests we are using optimistic locking by using a @Version field on our entities, simply retrying an operation on optimistic lock exceptions (with Spring Retry).

When either updating attributes of the same entity or using entityManager.lock(entity, OPTIMISTIC_FORCE_INCREMENT) in parallel, deadlocks are detected.
What we would expect here would either be a javax.persistence.OptimisticLockException or a org.springframework.orm.ObjectOptimisticLockingFailureException. After all, deadlocks should only be caused by pessimistic locks. And the problem with deadlocks in Oracle DB is that they are only detected after a timeout, sometimes.

For reproducibility we have included an example which uses entityManager.lock(entity, OPTIMISTIC_FORCE_INCREMENT).
You can find the example here: https://github.com/ccschneidr/hibernate-deadlock-example/

The major parts of the example are

  • an Entity called ApplicationUser with an int attribute, annotated with @Version
  • a test which executes two version increments in different order, simultaneously, to simulate more complex operations where the order of modifications cannot be controlled easily:
import jakarta.persistence.EntityManager;
import jakarta.persistence.LockModeType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DeadlockExamplesApplicationTests {

    @Autowired
    UserRepository userRepository;

    @Autowired
    Persistence persistence;

    @Autowired
    EntityManager entityManager;

    @Test
    public void testDeadlock() throws Exception {
        Integer userId1 = persistence.transactional(() ->
                userRepository.save(new ApplicationUser()).getUserid());

        Integer userId2 = persistence.transactional(() ->
                userRepository.save(new ApplicationUser()).getUserid());

        Thread thread1 = new Thread(() -> {
            try {
                persistence.transactional(() -> {
                    ApplicationUser applicationUser1 = userRepository.findById(userId1)
                            .orElseThrow(() -> new IllegalStateException("Previously created user not found"));
                    ApplicationUser applicationUser2 = userRepository.findById(userId2)
                            .orElseThrow(() -> new IllegalStateException("Previously created user not found"));

                    entityManager.lock(applicationUser1, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                    entityManager.lock(applicationUser2, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                    return null;
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, "thread1");

        Thread thread2 = new Thread(() -> {
            try {
                persistence.transactional(() -> {
                    ApplicationUser applicationUser1 = userRepository.findById(userId1)
                            .orElseThrow(() -> new IllegalStateException("Previously created user not found"));
                    ApplicationUser applicationUser2 = userRepository.findById(userId2)
                            .orElseThrow(() -> new IllegalStateException("Previously created user not found"));

                    entityManager.lock(applicationUser2, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                    entityManager.lock(applicationUser1, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                    return null;
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, "thread2");

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
    }
}

As far as we saw in the SQL statements Hibernate does not explicitly lock tables/row, but the underlying database (H2 in the example, Oracle in real life) does. But this renders the ‘optimistic’ locks non-functional in our case.

The question is: How can we avoid deadlocks and completely rely on Hibernate’s optimistic locking concept with the version number?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật