SlideShare a Scribd company logo
Hibernate Concurrency

Introduction
Concurrency control in hibernate do not use any additional locking mechanism
but relies on database connection concurrency controls.




Unit of Work
A unit of work of a web user can span multiple requests or database
operations. Most commonly used pattern for such a web application is
session per request model. A new session is created for every client
request and closed once the response is generated.
A database transaction is created once the session is opened and the
transaction 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 database
for single unit of work. Such series of database transactions can
be atomic, if only the last transaction updates/inserts rows in the
database and all others only execute select query.

All transactions have to be begin,committed and rolled back
explicitly. Hibernate automatically disables auto commit mode when
fetching a new jdbc connection.

The following are used in conjunction with above for concurrency
control

   ●   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 environment
Session s = factory.openSession();
Transaction tx = null;
try{
tx= s.beginTransaction();
//do work

tx.commit(); //automatically flushes the session.
}catch(RuntimeException e){
if(tx!=null)tx.rollback();

throw e;

}finally {
s.close();
}




Optimistic Concurrency Control

Optimistic concurrency control is the approach used in highly scalable
and concurrent applications. Hibernate provides three approaches for
writing 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
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 Versioning

optimistic-lock property is used to customize hibernate automatic
versioning. It defaults to version - hibernate uses version column to
check concurrent modification.

Other values that it can be set to are all, dirty and none.
all: All fields are used for version check. the update statement has
where clause that compares all previous and current values.

dirty: If concurrent modifications can be permitted if changes do not
overlap.




Pessimistic Concurrency Control
Pessimistic lock can be obtained by calling lock on the object. Hibernate
uses the locking mechanism of underlying database. It does not lock objects
in memory.Pessimistic locking is useful in scenarios where possibility of
simultaneous update to same row is high.

The explicit lock request is issued in one of the below ways
session.lock();
session.load - with lockmode parameter
Query.setLockMode()

If lockmode is not supported by database, hibernate uses alternate mechanism
instead of throwing exception to make applications portable.

Lock Modes:
LockMode.Write: This lock is automatically acquired on the object when
hibernate updates or inserts a row.

Lockmode.upgrade : is acquired by explicit select for update call.

Lockmode.upgrage_nowait

Lockmode.read is automatically acquired when hibernate reads a row under
repeatable read or serializable isolation levels. It can be explicitly
acquired also.


LockMode.NONE: This is absence of locks. All objects switch to this lock mode
at the end of transaction.

More Related Content

PDF
TAO and the Essence of Modern JavaScript
PPTX
Welcome to rx java2
PPTX
Architectural Patterns - Interactive and Event Handling Patterns
PDF
Active Object Design Pattern
PPTX
Reproducible component tests using docker
ODP
Java Concurrency, Memory Model, and Trends
PDF
Batch Processing - Processamento em Lotes no Mundo Corporativo
ODP
Fluxxor react library
TAO and the Essence of Modern JavaScript
Welcome to rx java2
Architectural Patterns - Interactive and Event Handling Patterns
Active Object Design Pattern
Reproducible component tests using docker
Java Concurrency, Memory Model, and Trends
Batch Processing - Processamento em Lotes no Mundo Corporativo
Fluxxor react library

What's hot (20)

PPTX
Architectural patterns part 4
PDF
Rx java2 - Should I use it?
PPTX
Java concurrency in practice
DOCX
Step types
PPTX
동기화 시대를 뛰어넘는 비동기 프로그래밍
PDF
Android framework design and development
PDF
Callback Function
PPTX
Enterprise Design Pattern: ACID principal ,Concurrency Patterns
PPTX
Not yet reactive but asyncronous mvc
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
PDF
Intro to Asynchronous Javascript
PDF
JavaScript Execution Context
PDF
Building Hermetic Systems (without Docker)
PPTX
Introduction to RxJS
PPTX
An introduction to Object Oriented JavaScript
PPTX
React hooks
RTF
NinjaSynch
PPTX
07 windows runtime app lifecycle
PDF
Understanding solid principles
PDF
Introduction to Unit Testing (Part 1 of 2)
Architectural patterns part 4
Rx java2 - Should I use it?
Java concurrency in practice
Step types
동기화 시대를 뛰어넘는 비동기 프로그래밍
Android framework design and development
Callback Function
Enterprise Design Pattern: ACID principal ,Concurrency Patterns
Not yet reactive but asyncronous mvc
Asynchronous JavaScript Programming with Callbacks & Promises
Intro to Asynchronous Javascript
JavaScript Execution Context
Building Hermetic Systems (without Docker)
Introduction to RxJS
An introduction to Object Oriented JavaScript
React hooks
NinjaSynch
07 windows runtime app lifecycle
Understanding solid principles
Introduction to Unit Testing (Part 1 of 2)
Ad

Similar to Hibernate concurrency (20)

PPT
05 Transactions
PPT
09 Application Design
PPTX
A beginner's guide to eventloops in node
PPTX
UNIT IV DIS.pptx
PDF
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
PPT
Hibernate Session 3
PPTX
Academy PRO: HTML5 Data storage
PPT
04 Data Access
PPT
Monitor(karthika)
PPTX
Vani dbms
PPTX
Concurrency: Mutual Exclusion and Synchronization
PPTX
Transaction management
PDF
Distributed fun with etcd
PPTX
Concurrency
PPT
02 Hibernate Introduction
PPTX
Concurrency Control in Distributed Database.
PPTX
Multiprocessing.pptx
PPTX
Presentation: Everything you wanted to know about writing async, high-concurr...
DOC
Concurrency Learning From Jdk Source
05 Transactions
09 Application Design
A beginner's guide to eventloops in node
UNIT IV DIS.pptx
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
Hibernate Session 3
Academy PRO: HTML5 Data storage
04 Data Access
Monitor(karthika)
Vani dbms
Concurrency: Mutual Exclusion and Synchronization
Transaction management
Distributed fun with etcd
Concurrency
02 Hibernate Introduction
Concurrency Control in Distributed Database.
Multiprocessing.pptx
Presentation: Everything you wanted to know about writing async, high-concurr...
Concurrency Learning From Jdk Source
Ad

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Machine Learning_overview_presentation.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Approach and Philosophy of On baking technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Cloud computing and distributed systems.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
Per capita expenditure prediction using model stacking based on satellite ima...
sap open course for s4hana steps from ECC to s4
Machine Learning_overview_presentation.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Approach and Philosophy of On baking technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Cloud computing and distributed systems.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Machine learning based COVID-19 study performance prediction
Digital-Transformation-Roadmap-for-Companies.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Empathic Computing: Creating Shared Understanding
Advanced methodologies resolving dimensionality complications for autism neur...

Hibernate concurrency

  • 1. Hibernate Concurrency Introduction Concurrency control in hibernate do not use any additional locking mechanism but relies on database connection concurrency controls. Unit of Work A unit of work of a web user can span multiple requests or database operations. Most commonly used pattern for such a web application is session per request model. A new session is created for every client request and closed once the response is generated. A database transaction is created once the session is opened and the transaction 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 database for single unit of work. Such series of database transactions can be atomic, if only the last transaction updates/inserts rows in the database and all others only execute select query. All transactions have to be begin,committed and rolled back explicitly. Hibernate automatically disables auto commit mode when fetching a new jdbc connection. The following are used in conjunction with above for concurrency control ● 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 environment Session s = factory.openSession(); Transaction tx = null;
  • 2. try{ tx= s.beginTransaction(); //do work tx.commit(); //automatically flushes the session. }catch(RuntimeException e){ if(tx!=null)tx.rollback(); throw e; }finally { s.close(); } Optimistic Concurrency Control Optimistic concurrency control is the approach used in highly scalable and concurrent applications. Hibernate provides three approaches for writing 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. 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 Versioning optimistic-lock property is used to customize hibernate automatic versioning. It defaults to version - hibernate uses version column to check concurrent modification. Other values that it can be set to are all, dirty and none.
  • 4. all: All fields are used for version check. the update statement has where clause that compares all previous and current values. dirty: If concurrent modifications can be permitted if changes do not overlap. Pessimistic Concurrency Control Pessimistic lock can be obtained by calling lock on the object. Hibernate uses the locking mechanism of underlying database. It does not lock objects in memory.Pessimistic locking is useful in scenarios where possibility of simultaneous update to same row is high. The explicit lock request is issued in one of the below ways session.lock(); session.load - with lockmode parameter Query.setLockMode() If lockmode is not supported by database, hibernate uses alternate mechanism instead of throwing exception to make applications portable. Lock Modes: LockMode.Write: This lock is automatically acquired on the object when hibernate updates or inserts a row. Lockmode.upgrade : is acquired by explicit select for update call. Lockmode.upgrage_nowait Lockmode.read is automatically acquired when hibernate reads a row under repeatable read or serializable isolation levels. It can be explicitly acquired also. LockMode.NONE: This is absence of locks. All objects switch to this lock mode at the end of transaction.