Nick Div
Nick Div

Reputation: 5628

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.

Upvotes: 1

Views: 1510

Answers (2)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153690

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.

Upvotes: 1

Ammar Bozorgvar
Ammar Bozorgvar

Reputation: 1278

To clarify the concept generate two scheduled jobs in quartz running every second to persist in your DB.

The bellow link contains the code.

https://github.com/bozorgvar/JTA-Locking/tree/master/src/transaction

check the following files:

  • schedule.java
  • HelloJob.java
  • HelloJob2.java

Upvotes: 0

Related Questions