Search code examples
hibernatepessimistic-locking

Hibernate Pessimistic Locking mode


I am trying to understand pessimistic locking mechanism in Hibernate (Over MySQL DB).

I tried running the following example:

    public static void main(String[] args) {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();
    Student student = null;
    Student studentTwo = null;
            try {
                session.beginTransaction();     
                student = (Student) session.get(Student.class, 1, LockMode.PESSIMISTIC_WRITE);
//I was hoping this line would thrown an error
                studentTwo = (Student) session.get(Student.class, 1, LockMode.PESSIMISTIC_WRITE);            
                System.out.println(student.getName());
                System.out.println(studentTwo.getName());
                student.setName("John Doe"); 
                session.getTransaction().commit();

                session.close();
            }catch(HibernateException ex){

            }
    }

But instead of giving me an error it just executes fine. Is there some sort of concept that I have misunderstood. Is this behavior normal?

I was able to test Optimistic locking perfectly fine so for pessimistic locking is there some misunderstanding of the concept or there is something that my code is missing.


Solution

  • You are using a single session and a single transaction too. The database locks are re-entrant, as otherwise you would end up deadlocking by yourself.

    Change your example to start two sessions, each one with its own transaction. Then you'll see the second transaction waiting for the first one to release the acquired locks.