Hibernate: Deadlock found when trying to obtain lock

后端 未结 2 1047
感动是毒
感动是毒 2021-02-04 09:29

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.

2条回答
  •  别那么骄傲
    2021-02-04 09:41

    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.SERIALIZABLEin 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:

       
    
        
        
    
    
        
        
    
    
    1. Can I somehow execute update query (either JPA/Native) without having to lock the table via @Transactional?

    Update queries are possible via native queries or JPQL.

    1. Can I somehow get into session without using @Transactional? For instance, scheduled thread tries to read Lazy field on Entity yields to LazyInitializationException - no session, if the method is not annotated with @Transactional

    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.

提交回复
热议问题