Hibernate concurrency


Published on

Published in: Technology
1 Comment
  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Hibernate concurrency

  1. 1. Hibernate ConcurrencyIntroductionConcurrency control in hibernate do not use any additional locking mechanismbut relies on database connection concurrency controls.Unit of WorkA unit of work of a web user can span multiple requests or databaseoperations. Most commonly used pattern for such a web application issession per request model. A new session is created for every clientrequest and closed once the response is generated.A database transaction is created once the session is opened and thetransaction gets committed just before closing the session.So for every session there exists a corresponding transaction.For long conversations, a user does multiple interaction with databasefor single unit of work. Such series of database transactions canbe atomic, if only the last transaction updates/inserts rows in thedatabase and all others only execute select query.All transactions have to be begin,committed and rolled backexplicitly. Hibernate automatically disables auto commit mode whenfetching a new jdbc connection.The following are used in conjunction with above for concurrencycontrol ● Automatic Versioning : HIbernate can automatically version database rows, so concurrent modification can be detected. ● Detached Objects: Is session per request model is used, then session is closed during user’s think time. The detached objects can are reattached with new session when a new request arrives. ● Long Session: With session per conversation approach, a session is not closed when a response is sent. The underlying jdbc connection is released. This approach does not require objects to be reattached. Session is flushed explicitly at the end of conversation and automatic versioning is used to check concurrent modification.Control flow in non managed environmentSession s = factory.openSession();Transaction tx = null;
  2. 2. try{tx= s.beginTransaction();//do worktx.commit(); //automatically flushes the session.}catch(RuntimeException e){if(tx!=null)tx.rollback();throw e;}finally {s.close();}Optimistic Concurrency ControlOptimistic concurrency control is the approach used in highly scalableand concurrent applications. Hibernate provides three approaches forwriting application code that uses optimistic concurrency control. ● Application Version Checking: Application reloads the persistent state in a new session. The version column value before and after loading is compared. If the value is same, then no concurrent modification has taken place. The version column is mapped using <version> tag. The version value is automatically incremented by hibernate during flush if entity is dirty. Session s = factory.openSession(); Transaction t = s.beginTransaction(); int old_v = entity.getVersion(); s.load(entity, entity.getKey()); int new_v= entity.getVersion(); if(old_v!=new_v) throw new exception(); //do work ● Automatic version checking in extended session In session per conversation approach, same session is used for multiple requests of a conversation. For a new request of the conversation, database transaction is initiated. Automatic version checking is done at flush time and an exception is thrown if concurrent modification is detected.. Flush is called manually only for last transaction of the conversation. This is done by
  3. 3. setting flush mode to manual so that transaction commit do not call flush automatically. The session is disconnected from underlying database transaction at the end of transaction. The application does not reattach or reload database instances, nor it does version checking. Version checking is taken care by hibernate. Hibernate does version check by using an update query with appropriate where clause. Ex: update person set version=?, name=?, address=? where id=? and version=? // foo is an instance loaded earlier by the old session Transaction t = session.beginTransaction(); // Obtain a new JDBC connection, start transaction foo.setProperty("bar"); session.flush(); // Only for last transaction in conversation t.commit(); // Also return JDBC connection session.close(); // Only for last transaction in conversation To force a version check before calling flush, session.lock with LockMode.Read can be called. An exception is thrown if the object was updated by any other transaction. ● Detached object with automatic versioning A new session is created for every request. The detached objects are reattached using session.save() or session.saveOrUpdate(), session.merge() Hibernate checks for version during flush throwing exception if concurrent modification is detected. To force a version check , session.lock() can be called with LockMode.Read.Automatic Versioningoptimistic-lock property is used to customize hibernate automaticversioning. It defaults to version - hibernate uses version column tocheck concurrent modification.Other values that it can be set to are all, dirty and none.
  4. 4. all: All fields are used for version check. the update statement haswhere clause that compares all previous and current values.dirty: If concurrent modifications can be permitted if changes do notoverlap.Pessimistic Concurrency ControlPessimistic lock can be obtained by calling lock on the object. Hibernateuses the locking mechanism of underlying database. It does not lock objectsin memory.Pessimistic locking is useful in scenarios where possibility ofsimultaneous update to same row is high.The explicit lock request is issued in one of the below wayssession.lock();session.load - with lockmode parameterQuery.setLockMode()If lockmode is not supported by database, hibernate uses alternate mechanisminstead of throwing exception to make applications portable.Lock Modes:LockMode.Write: This lock is automatically acquired on the object whenhibernate updates or inserts a row.Lockmode.upgrade : is acquired by explicit select for update call.Lockmode.upgrage_nowaitLockmode.read is automatically acquired when hibernate reads a row underrepeatable read or serializable isolation levels. It can be explicitlyacquired also.LockMode.NONE: This is absence of locks. All objects switch to this lock modeat the end of transaction.