liveBook · Manning

Deadlock

As explained in Java Persistence with Spring Data and Hibernate epub

A deadlock is a cyclic waiting condition in which concurrent transactions each hold locks needed by another and none can proceed.

A deadlock occurs when concurrent transactions hold locks that the other transactions need. Each transaction waits for a lock release, so none can proceed. Databases may detect the cycle and abort one transaction immediately, or terminate one after a timeout; the surviving transaction can then continue. section 11.2.4

Opposite update order

One transaction updates Item 1 and then Item 2, while another updates Item 2 and then Item 1. Hibernate flushes the changes as SQL updates, leaving each transaction holding one row lock while waiting for the other. The database may abort one transaction. section 11.2.4

Reduce the probability or scope of deadlocks by:

  • Ordering updates by primary key so concurrent transactions acquire row locks consistently; Hibernate supports this through the hibernate.order_updates persistence-unit setting. section 11.2.4
  • Using serializable isolation when updating a single row should make concurrent work wait on the table rather than interleave conflicting row locks. section 11.2.4
  • Acquiring exclusive locks when selecting data so competing transactions wait until the locks are released. section 11.2.3 section 11.2.4
  • Treating deadlock handling as an operational concern: light testing may miss cycles that appear under production transaction load, and aborted transactions are difficult to recover from in application code. section 11.2.4

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Traces opposing row-update orders through Hibernate flushes and compares isolation, exclusive locks, and ordered updates.
Examples
Uses two Item entities, opposing SQL UPDATE orders, exclusive locks, serializable isolation, and production transaction load.
What you can do after
Diagnose/debug with it by recognizing conflicting update order and configure Hibernate to order updates consistently.
How it connects
Connects deadlocks with pessimistic locking, transaction isolation, database locks, Hibernate flushing, and transaction failure recovery.

Also explained in

Compare how 15 books explain deadlock →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.