As per Read LockMode in Hibernate docs It is a shared lock. Objects in this lock mode were read from the database in the current transaction, rather than being pulled from a cache.
SessionFactory sessions = new Configuration().configure().buildSessionFactory();
Session session = sessions.openSession();
Transaction tx = null;
tx = session.beginTransaction();
Person p1 = (Person)session. get(Person.class,1);//line 1
p1 = (Person)session. get(Person.class,1);//line 2
session. lock(p1, LockMode.READ);//line 3
p1 = (Person)session. get(Person.class,1);//line4
p1 = (Person)session. get(Person.class,1);//line 5
Now as per shared lock definition holding share locks to prevent concurrent access by a writer with the code snippet above , i made the thread to hold at line 4(so it has acquired the lock in read mode at this point of time).Now i tried to update the person with id 1 from another thread, it succeeded. Not sure why, because as per definition holding share locks to prevent concurrent access by a writer
As Read lock mode says Objects in this lock mode were read from the database in the current transaction, rather than being pulled from a cache . Bt in my code snippet at line 4 and line 5 it did not get the row from database for id 1, it got from session only.Why?
Last question on None Lock Mode. As per documentation No lock required. If an object is requested with this lock mode, a READ lock will be obtained if it is necessary to actually read the state from the database, rather than pull it from a cache. As stated no lock acquired then why would developer acquire this lock, as this would be default. Right?
How about when a thread 1 is just about to write an entity to the database and thread 2 is going to read the same entity from it? Either one of them should get a lock to read or write the data. If thread1 gets the write lock, thread 2 must wait till the write is complete. However, if thread 2 gets the read lock, thread 1 has no problem in going in and writing the data. This is so because when thread 2 reads the records in a consistent state. It becomes stale only after thread 1 has written to the database (Although, a write on this object from thread 2 will trigger a stale state exception in case of a versioned entity). Read locks are meant for preventing inconsistency and not freeze the record for further update by the same transaction. You can achieve that behaviour using write locks.
Again the read lock is accquired in order to prevent the entity to be in an inconsistent state. From the cache it wont be a problem. The developer does not need to specify the Read lock when doing a fetch, it should be managed internally by the persistence provider.