I am using hibernate in my project and I am getting random Apparent Deadlocks for very simple database operations.
There is one of the Stack Traces: https://gist.github.
Because the deadlocks happen so frequently, it looks like some of the threads of the application are holding locks for an extended period of time.
Each thread in the application will use it's own database connection/connections while accessing the database, so from the point of view of the database two threads are two distinct clients that compete for database locks.
If a thread holds locks for an extended period of time and acquires them in a certain order, and a second thread comes along acquiring the same locks but on a different order, deadlock is bound to occur (see here for details on this frequent deadlock cause).
Also deadlocks are occurring in read operations, which means that some threads are acquiring read locks as well. This happens if the threads are running transactions in REPEATABLE_READ
isolation level or SERIALIZABLE
.
To solve this, try searching for usages of Isolation.REPEATABLE_READ
and Isolation.SERIALIZABLE
in the project, to see if this is being used.
As an alternative, use the default READ_COMMITTED
isolation level and annotate the entities with @Version
, to handle concurrency using optimistic locking instead.
Also try to identify long running transactions, this happens sometimes when the @Transactional
is placed at the wrong place and wraps for example the processing of a whole file in the example of a batch processing, instead of doing transactions line by line.
This a log4j configuration to log the creation/deletion of entity managers and transactions begin/commit/rollback:
Update queries are possible via native queries or JPQL.
In methods without @Transactional
, queries will be executed in it's own entity manager and return only detached entities, as thee session is closed immediatelly after the query is run.
so the lazy initialization exceptions in methods without @Transactional
is normal. You can set them to @Transactional(readOnly=true)
as well.