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.
Ad

More Related Content

What's hot (20)

Architectural patterns part 4
Architectural patterns part 4Architectural patterns part 4
Architectural patterns part 4
assinha
 
Rx java2 - Should I use it?
Rx java2 - Should I use it?Rx java2 - Should I use it?
Rx java2 - Should I use it?
Kamil Kucharski
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
Step types
Step typesStep types
Step types
vamshimahi
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
명신 김
 
Android framework design and development
Android framework design and developmentAndroid framework design and development
Android framework design and development
ramalinga prasad tadepalli
 
Callback Function
Callback FunctionCallback Function
Callback Function
Roland San Nicolas
 
Enterprise Design Pattern: ACID principal ,Concurrency Patterns
Enterprise Design Pattern:ACID principal,Concurrency PatternsEnterprise Design Pattern:ACID principal,Concurrency Patterns
Enterprise Design Pattern: ACID principal ,Concurrency Patterns
Sergey Bandysik
 
Not yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvcNot yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvc
Dmitry Aleksandrov
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
Juan Medina
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
William Farrell
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScript
TO THE NEW | Technology
 
React hooks
React hooksReact hooks
React hooks
Sadhna Rana
 
NinjaSynch
NinjaSynchNinjaSynch
NinjaSynch
Thomas Knudstrup
 
07 windows runtime app lifecycle
07   windows runtime app lifecycle07   windows runtime app lifecycle
07 windows runtime app lifecycle
WindowsPhoneRocks
 
Understanding solid principles
Understanding solid principlesUnderstanding solid principles
Understanding solid principles
Babatunde Otaru
 
Introduction to Unit Testing (Part 1 of 2)
Introduction to Unit Testing (Part 1 of 2)Introduction to Unit Testing (Part 1 of 2)
Introduction to Unit Testing (Part 1 of 2)
Dennis Byrne
 
Architectural patterns part 4
Architectural patterns part 4Architectural patterns part 4
Architectural patterns part 4
assinha
 
Rx java2 - Should I use it?
Rx java2 - Should I use it?Rx java2 - Should I use it?
Rx java2 - Should I use it?
Kamil Kucharski
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
명신 김
 
Enterprise Design Pattern: ACID principal ,Concurrency Patterns
Enterprise Design Pattern:ACID principal,Concurrency PatternsEnterprise Design Pattern:ACID principal,Concurrency Patterns
Enterprise Design Pattern: ACID principal ,Concurrency Patterns
Sergey Bandysik
 
Not yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvcNot yet reactive but asyncronous mvc
Not yet reactive but asyncronous mvc
Dmitry Aleksandrov
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
Juan Medina
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
William Farrell
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScript
TO THE NEW | Technology
 
07 windows runtime app lifecycle
07   windows runtime app lifecycle07   windows runtime app lifecycle
07 windows runtime app lifecycle
WindowsPhoneRocks
 
Understanding solid principles
Understanding solid principlesUnderstanding solid principles
Understanding solid principles
Babatunde Otaru
 
Introduction to Unit Testing (Part 1 of 2)
Introduction to Unit Testing (Part 1 of 2)Introduction to Unit Testing (Part 1 of 2)
Introduction to Unit Testing (Part 1 of 2)
Dennis Byrne
 

Similar to Hibernate concurrency (20)

05 Transactions
05 Transactions05 Transactions
05 Transactions
Ranjan Kumar
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
concurrency control.ppt
concurrency control.pptconcurrency control.ppt
concurrency control.ppt
BikalAdhikari4
 
A beginner's guide to eventloops in node
A beginner's guide to eventloops in nodeA beginner's guide to eventloops in node
A beginner's guide to eventloops in node
Fibonalabs
 
UNIT IV DIS.pptx
UNIT IV DIS.pptxUNIT IV DIS.pptx
UNIT IV DIS.pptx
Premkumar R
 
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxcAdvanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
alemunuruhak9
 
Hibernate Session 3
Hibernate Session 3Hibernate Session 3
Hibernate Session 3
b_kathir
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
Binary Studio
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
Ranjan Kumar
 
Monitor(karthika)
Monitor(karthika)Monitor(karthika)
Monitor(karthika)
Nagarajan
 
Vani dbms
Vani dbmsVani dbms
Vani dbms
SangeethaSasi1
 
Concurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and SynchronizationConcurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and Synchronization
Anas Ebrahim
 
Transaction management
Transaction managementTransaction management
Transaction management
ArchanaMani2
 
Distributed fun with etcd
Distributed fun with etcdDistributed fun with etcd
Distributed fun with etcd
Abdulaziz AlMalki
 
Concurrency
ConcurrencyConcurrency
Concurrency
Ankur Maheshwari
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
 
Concurrency Control in Distributed Database.
Concurrency Control in Distributed Database.Concurrency Control in Distributed Database.
Concurrency Control in Distributed Database.
Meghaj Mallick
 
Multiprocessing.pptx
Multiprocessing.pptxMultiprocessing.pptx
Multiprocessing.pptx
MaheshGour5
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
Baruch Sadogursky
 
Rdbms
RdbmsRdbms
Rdbms
sakthibalabalamuruga
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
concurrency control.ppt
concurrency control.pptconcurrency control.ppt
concurrency control.ppt
BikalAdhikari4
 
A beginner's guide to eventloops in node
A beginner's guide to eventloops in nodeA beginner's guide to eventloops in node
A beginner's guide to eventloops in node
Fibonalabs
 
UNIT IV DIS.pptx
UNIT IV DIS.pptxUNIT IV DIS.pptx
UNIT IV DIS.pptx
Premkumar R
 
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxcAdvanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
Advanced Database Chapter 4.pdf shnsbxlajmndm woweosmkl m,xcnkl C NOOxcx xcbnxc
alemunuruhak9
 
Hibernate Session 3
Hibernate Session 3Hibernate Session 3
Hibernate Session 3
b_kathir
 
Academy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storageAcademy PRO: HTML5 Data storage
Academy PRO: HTML5 Data storage
Binary Studio
 
Monitor(karthika)
Monitor(karthika)Monitor(karthika)
Monitor(karthika)
Nagarajan
 
Concurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and SynchronizationConcurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and Synchronization
Anas Ebrahim
 
Transaction management
Transaction managementTransaction management
Transaction management
ArchanaMani2
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
Ranjan Kumar
 
Concurrency Control in Distributed Database.
Concurrency Control in Distributed Database.Concurrency Control in Distributed Database.
Concurrency Control in Distributed Database.
Meghaj Mallick
 
Multiprocessing.pptx
Multiprocessing.pptxMultiprocessing.pptx
Multiprocessing.pptx
MaheshGour5
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
Baruch Sadogursky
 
Ad

Recently uploaded (20)

Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Vasileios Komianos
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
React Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for SuccessReact Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for Success
Amelia Swank
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
DNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in NepalDNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in Nepal
ICT Frame Magazine Pvt. Ltd.
 
Top Hyper-Casual Game Studio Services
Top  Hyper-Casual  Game  Studio ServicesTop  Hyper-Casual  Game  Studio Services
Top Hyper-Casual Game Studio Services
Nova Carter
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Digital Technologies for Culture, Arts and Heritage: Insights from Interdisci...
Vasileios Komianos
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
React Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for SuccessReact Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for Success
Amelia Swank
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
Top Hyper-Casual Game Studio Services
Top  Hyper-Casual  Game  Studio ServicesTop  Hyper-Casual  Game  Studio Services
Top Hyper-Casual Game Studio Services
Nova Carter
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Ad

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.
  翻译: