SlideShare a Scribd company logo
Transactions and
Concurrency Control
Patterns
VLAD MIHALCEA
About me
• @Hibernate Developer
• vladmihalcea.com
• @vlad_mihalcea
• vladmihalcea
Google Developers
“We believe it is better to have application
programmers deal with performance problems
due to overuse of transactions as bottlenecks arise,
rather than always coding around
the lack of transactions.”
Spanner: Google’s Globally-Distributed Database - https://static.googleusercontent.com/media/research.google.com/en//archive/spanner-osdi2012.pdf
Database transactions
• Every statement is executed in the context of a transaction
• There are two types of transactions:
• Implicit – auto-commit
• Explicit – BEGIN, COMMIT or ROLLBACK
History of ACID
In SQL-86, there were only three transaction properties:
• Consistency
• Atomicity
• Durability
The Transaction Concept: Virtues and Limitations http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
Atomicity
Atomicity
• Atomicity requires rolling back
• Rolling back requires preventing dirty writes
Dirty Write Anomaly
Consistency
• Moving the database from one valid state to another.
• Constraint checks
• column types
• column length
• column nullability
• foreign key constraints
• unique key constraints
Consistency in CAP – Linearizability
Durability
• Durability ensures that all committed transaction changes become
permanent.
Durability
SQL-92 ACID
• Atomicity
• Consistency
• Isolation
• Durability
Serializability
• Interleaving concurrent transaction statements so that the outcome
is equivalent to a serial execution
Serial execution
Conflict
Dealing with Concurrency
• Avoid it
• VoltDB (in-memory, single-threaded, guarantees Serializability)
• Control it
• RDBMS (Concurrency Control and isolation levels)
Dealing with conflicts in RDBMS
• Conflict avoidance
• 2PL (Two-Phase Locking)
• Conflict detection
• MVCC (Multi-Version Concurrency Control)
Lock types
Compatibility matrix Shared Lock Exclusive lock
Shared Lock Allow Prevent
Exclusive lock Prevent Prevent
2PL
• Simple to reason about:
• Reads acquire shared locks
• Writes acquire exclusive locks
• The 2PL protocol:
• expanding phase (acquire locks, release no lock)
• shrinking phase (release all locks, no further lock acquisition)
Cost of locking
Challenges have changed
“At present [1981], the largest airlines and
banks have about 10,000 terminals and about
100 active transactions at any instant.
These transactions live for a second or two and are
gone forever.”
The Transaction Concept: Virtues and Limitations - http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
MVCC
• Readers don’t block writers and writers don’t block readers.
• Writers block writers to prevent Dirty Writes.
MVCC – Insert row (PostgreSQL)
MVCC – Delete row (PostgreSQL)
MVCC – Update row (PostgreSQL)
MVCC
• Two types of snapshots:
• Query-level: Read Committed
• Transaction-level: Snapshot Isolation
• Watch out for long-running transactions
Phenomena
• The SQL-92 standard introduced three phenomena:
• dirty read
• non-repeatable read
• phantom read.
• In reality, there are more:
• dirty write
• read skew
• write skew
• lost update.
Dirty Read
Non-Repeatable Read
Phantom Read
Read Skew
Write Skew
Lost Update
2PL – Phantom Read
MVCC – Phantom Read
MVCC – Phantom Read?
SQL Standard Isolation Levels
Isolation
Level Dirty Read
Non-
Repeatable
Read
Phantom
Read
Read
Uncommitted Yes Yes Yes
Read
Committed No Yes Yes
Repeatable
Read No No Yes
Serializable No No No
Oracle Isolation Levels
Isolation
Level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Committed No Yes Yes Yes Yes Yes
Serializable No No No No Yes No
SQL Server Isolation Levels
Isolation level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Uncommitted Yes Yes Yes Yes Yes Yes
Read
Committed No Yes Yes Yes Yes Yes
Repeatable
Read No No Yes No No No
Serializable No No No No No No
Read
Committed SI No Yes Yes Yes Yes Yes
Snapshot
Ioslation No No No No Yes No
PostgreSQL Isolation Levels
Isolation level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Uncommitted No Yes Yes Yes Yes Yes
Read
Committed No Yes Yes Yes Yes Yes
Repeatable
Read No No No No Yes No
Serializable No No No No No No
MySQL Isolation Levels
Isolation level Dirty Read
Non-
Repeatable
Read
Phantom
Read Read Skew Write Skew Lost Update
Read
Uncommitted Yes Yes Yes Yes Yes Yes
Read
Committed No Yes Yes Yes Yes Yes
Repeatable
Read No No No No Yes Yes
Serializable No No No No No No
Beyond ACID
• ACID is not sufficient
• What about multi-request logical transactions?
Stateless conversation lost update
Stateful conversation lost update
Version-based optimistic locking
@Version
private int version;
UPDATE post
SET
name = ‘Name’, version = 1
WHERE
id = 1 AND version = 0
Stateful versioned conversation
Write concerns
False positives
Write-based schema mapping
Non-overlapping writes
Versionless optimistic locking
@Entity
@Table(name = "post")
@DynamicUpdate
@OptimisticLocking(type = OptimisticLockType.DIRTY)
public class Post {
@Id
private Long id;
private String title;
private long views;
private int likes;
}
Non-overlapping writes
Explicit optimistic locking modes
Lock Mode Type Description
NONE In the absence of explicit locking, the application will use implicit locking (optimistic or pessimistic)
OPTIMISTIC
Always issues a version check upon transaction commit, therefore ensuring optimistic locking
repeatable reads.
READ Same as OPTIMISTIC.
OPTIMISTIC_FORCE_INCREMENT
Always increases the entity version (even when the entity doesn’t change) and issues a version
check upon transaction commit, therefore ensuring optimistic locking repeatable reads.
WRITE Same as OPTIMISTIC_FORCE_INCREMENT.
PESSIMISTIC_READ
A shared lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_WRITE
lock.
PESSIMISTIC_WRITE
An exclusive lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ
or a PESSIMISTIC_WRITE lock.
PESSIMISTIC_FORCE_INCREMENT
A database lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or
a PESSIMISTIC_WRITE lock and the entity version is incremented upon transaction commit.
LockModeType.OPTIMISTIC_FORCE_INCREMENT
LockModeType.OPTIMISTIC_FORCE_INCREMENT
Repository repository = entityManager.find(Repository.class, 1L,
LockModeType.OPTIMISTIC_FORCE_INCREMENT);
executeSync(() -> {
doInJPA(_entityManager -> {
Repository _repository = _entityManager.find(Repository.class, 1L,
LockModeType.OPTIMISTIC_FORCE_INCREMENT);
Commit _commit = new Commit(_repository);
_commit.getChanges().add(new Change("Intro.md", "0a1,2..."));
_entityManager.persist(_commit);
});
});
Commit commit = new Commit(repository);
commit.getChanges().add(new Change("FrontMatter.md", "0a1,5..."));
commit.getChanges().add(new Change("HibernateIntro.md", "17c17..."));
entityManager.persist(commit);
LockModeType.OPTIMISTIC_FORCE_INCREMENT
Thank you
Questions and Answers

More Related Content

What's hot (19)

PDF
Infinum Android Talks #09 - DBFlow ORM
Infinum
 
PPTX
Apache Cayenne: a Java ORM Alternative
Andrus Adamchik
 
PDF
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Bob Pusateri
 
PPTX
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
Malin Weiss
 
PDF
ITB2017 - Slaying the ORM dragons with cborm
Ortus Solutions, Corp
 
PPTX
A tour of Java and the JVM
Alex Birch
 
PPTX
/path/to/content - the Apache Jackrabbit content repository
Jukka Zitting
 
PPTX
REST Methodologies
jrodbx
 
PDF
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
J V
 
PPT
Java SE 7 New Features and Enhancements
Fu Cheng
 
PDF
Scala Frameworks for Web Application 2016
takezoe
 
PDF
Jakarta EE 8 on JDK17
Rudy De Busscher
 
PDF
High-Performance Hibernate Devoxx France 2016
Vlad Mihalcea
 
PPTX
OSGifying the repository
Jukka Zitting
 
PDF
PHP, the GraphQL ecosystem and GraphQLite
JEAN-GUILLAUME DUJARDIN
 
PDF
Stardog 1.1: An Easier, Smarter, Faster RDF Database
kendallclark
 
PDF
Alfresco Content Modelling and Policy Behaviours
J V
 
PDF
JCR - Java Content Repositories
Carsten Ziegeler
 
PPT
Design and architecture of Jackrabbit
Jukka Zitting
 
Infinum Android Talks #09 - DBFlow ORM
Infinum
 
Apache Cayenne: a Java ORM Alternative
Andrus Adamchik
 
Locks, Blocks, and Snapshots: Maximizing Database Concurrency (PASS DBA Virtu...
Bob Pusateri
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
Malin Weiss
 
ITB2017 - Slaying the ORM dragons with cborm
Ortus Solutions, Corp
 
A tour of Java and the JVM
Alex Birch
 
/path/to/content - the Apache Jackrabbit content repository
Jukka Zitting
 
REST Methodologies
jrodbx
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
J V
 
Java SE 7 New Features and Enhancements
Fu Cheng
 
Scala Frameworks for Web Application 2016
takezoe
 
Jakarta EE 8 on JDK17
Rudy De Busscher
 
High-Performance Hibernate Devoxx France 2016
Vlad Mihalcea
 
OSGifying the repository
Jukka Zitting
 
PHP, the GraphQL ecosystem and GraphQLite
JEAN-GUILLAUME DUJARDIN
 
Stardog 1.1: An Easier, Smarter, Faster RDF Database
kendallclark
 
Alfresco Content Modelling and Policy Behaviours
J V
 
JCR - Java Content Repositories
Carsten Ziegeler
 
Design and architecture of Jackrabbit
Jukka Zitting
 

Viewers also liked (20)

PDF
High-Performance JDBC Voxxed Bucharest 2016
Vlad Mihalcea
 
PDF
High Performance Hibernate JavaZone 2016
Vlad Mihalcea
 
PDF
Navigating the Incubator at the Apache Software Foundation
Brett Porter
 
PDF
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
CodeFest
 
PPT
Вебинар начало
catarus
 
PPT
Tdd Workshop Disscussions
Evgeniy Krivosheev
 
PDF
Осознанность рефакторинга: Модель принятия инженерных решений
Evgeniy Krivosheev
 
PDF
Google GIN
Anh Quân
 
PDF
[Altibase] 6 what is the mvcc
altistory
 
PPTX
Hibernate inheritance and relational mappings with examples
Er. Gaurav Kumar
 
PDF
Введение в веб каркас Struts2
Evgeniy Krivosheev
 
PPT
Developing With JAAS
rahmed_sct
 
PDF
Mv unmasked.w.code.march.2013
EDB
 
PPT
Locking unit 1 topic 3
avniS
 
PDF
Building Rich Domain Models
Chris Richardson
 
PPTX
Hibernate working with criteria- Basic Introduction
Er. Gaurav Kumar
 
PPTX
Hibernate
Prashant Kalkar
 
PPTX
Transaction and concurrency control
Anil Shrestha
 
PDF
Pagination Done the Right Way
Markus Winand
 
PPTX
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Reactive.IO
 
High-Performance JDBC Voxxed Bucharest 2016
Vlad Mihalcea
 
High Performance Hibernate JavaZone 2016
Vlad Mihalcea
 
Navigating the Incubator at the Apache Software Foundation
Brett Porter
 
CodeFest 2013. Зиновьев А. — MyBatis & Hibernate, давайте жить дружно!
CodeFest
 
Вебинар начало
catarus
 
Tdd Workshop Disscussions
Evgeniy Krivosheev
 
Осознанность рефакторинга: Модель принятия инженерных решений
Evgeniy Krivosheev
 
Google GIN
Anh Quân
 
[Altibase] 6 what is the mvcc
altistory
 
Hibernate inheritance and relational mappings with examples
Er. Gaurav Kumar
 
Введение в веб каркас Struts2
Evgeniy Krivosheev
 
Developing With JAAS
rahmed_sct
 
Mv unmasked.w.code.march.2013
EDB
 
Locking unit 1 topic 3
avniS
 
Building Rich Domain Models
Chris Richardson
 
Hibernate working with criteria- Basic Introduction
Er. Gaurav Kumar
 
Hibernate
Prashant Kalkar
 
Transaction and concurrency control
Anil Shrestha
 
Pagination Done the Right Way
Markus Winand
 
Postgres MVCC - A Developer Centric View of Multi Version Concurrency Control
Reactive.IO
 
Ad

Similar to Transactions and Concurrency Control Patterns (20)

PDF
Transactions and Concurrency Control Patterns
J On The Beach
 
PPTX
MVCC for Ruby developers
Michał Młoźniak
 
PDF
Database transaction isolation and locking in Java
Constantine Slisenka
 
PPTX
Multi version Concurrency Control and its applications in Advanced database s...
GauthamSK4
 
PPT
Svetlin Nakov - Database Transactions
Svetlin Nakov
 
PPTX
Spring@transaction,isolation
Brahmani Gundlapalli
 
PDF
Transactions and Concurrency Control Patterns - 2019
Vlad Mihalcea
 
PPT
05 Transactions
Ranjan Kumar
 
PPTX
DBMS UNIT IV.pptx
Janagi Raman S
 
PPTX
Transaction
Sanjoy Kumar Roy
 
PPTX
Transactions in database systems and functions
janakiraman123
 
PDF
Dbms module iii
SANTOSH RATH
 
PPTX
DBMS: Week 13 - Transactions and Concurrency Control
RashidFaridChishti
 
PPTX
Transation in data base management system.pptx
ayush626953
 
PDF
Transaction Properties(ACID Properties)
Yaksh Jethva
 
ODP
Lecture 5. MS SQL. Transactions
Alexey Furmanov
 
KEY
NoSQL Databases: Why, what and when
Lorenzo Alberton
 
PDF
SQL Transactions - What they are good for and how they work
Markus Winand
 
PPT
Hibernate Session 3
b_kathir
 
PDF
MySQL Overview
Andrey Sidelev
 
Transactions and Concurrency Control Patterns
J On The Beach
 
MVCC for Ruby developers
Michał Młoźniak
 
Database transaction isolation and locking in Java
Constantine Slisenka
 
Multi version Concurrency Control and its applications in Advanced database s...
GauthamSK4
 
Svetlin Nakov - Database Transactions
Svetlin Nakov
 
Spring@transaction,isolation
Brahmani Gundlapalli
 
Transactions and Concurrency Control Patterns - 2019
Vlad Mihalcea
 
05 Transactions
Ranjan Kumar
 
DBMS UNIT IV.pptx
Janagi Raman S
 
Transaction
Sanjoy Kumar Roy
 
Transactions in database systems and functions
janakiraman123
 
Dbms module iii
SANTOSH RATH
 
DBMS: Week 13 - Transactions and Concurrency Control
RashidFaridChishti
 
Transation in data base management system.pptx
ayush626953
 
Transaction Properties(ACID Properties)
Yaksh Jethva
 
Lecture 5. MS SQL. Transactions
Alexey Furmanov
 
NoSQL Databases: Why, what and when
Lorenzo Alberton
 
SQL Transactions - What they are good for and how they work
Markus Winand
 
Hibernate Session 3
b_kathir
 
MySQL Overview
Andrey Sidelev
 
Ad

Recently uploaded (20)

PPTX
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
PPTX
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPTX
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
PPTX
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PDF
DevOps Design for different deployment options
henrymails
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
PPTX
本科硕士学历佛罗里达大学毕业证(UF毕业证书)24小时在线办理
Taqyea
 
PPTX
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
PPTX
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
PPT
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
PPTX
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
PDF
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
DevOps Design for different deployment options
henrymails
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
本科硕士学历佛罗里达大学毕业证(UF毕业证书)24小时在线办理
Taqyea
 
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
introductio to computers by arthur janry
RamananMuthukrishnan
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 

Transactions and Concurrency Control Patterns

  • 2. About me • @Hibernate Developer • vladmihalcea.com • @vlad_mihalcea • vladmihalcea
  • 3. Google Developers “We believe it is better to have application programmers deal with performance problems due to overuse of transactions as bottlenecks arise, rather than always coding around the lack of transactions.” Spanner: Google’s Globally-Distributed Database - https://static.googleusercontent.com/media/research.google.com/en//archive/spanner-osdi2012.pdf
  • 4. Database transactions • Every statement is executed in the context of a transaction • There are two types of transactions: • Implicit – auto-commit • Explicit – BEGIN, COMMIT or ROLLBACK
  • 5. History of ACID In SQL-86, there were only three transaction properties: • Consistency • Atomicity • Durability The Transaction Concept: Virtues and Limitations http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
  • 7. Atomicity • Atomicity requires rolling back • Rolling back requires preventing dirty writes
  • 9. Consistency • Moving the database from one valid state to another. • Constraint checks • column types • column length • column nullability • foreign key constraints • unique key constraints
  • 10. Consistency in CAP – Linearizability
  • 11. Durability • Durability ensures that all committed transaction changes become permanent.
  • 13. SQL-92 ACID • Atomicity • Consistency • Isolation • Durability
  • 14. Serializability • Interleaving concurrent transaction statements so that the outcome is equivalent to a serial execution
  • 17. Dealing with Concurrency • Avoid it • VoltDB (in-memory, single-threaded, guarantees Serializability) • Control it • RDBMS (Concurrency Control and isolation levels)
  • 18. Dealing with conflicts in RDBMS • Conflict avoidance • 2PL (Two-Phase Locking) • Conflict detection • MVCC (Multi-Version Concurrency Control)
  • 19. Lock types Compatibility matrix Shared Lock Exclusive lock Shared Lock Allow Prevent Exclusive lock Prevent Prevent
  • 20. 2PL • Simple to reason about: • Reads acquire shared locks • Writes acquire exclusive locks • The 2PL protocol: • expanding phase (acquire locks, release no lock) • shrinking phase (release all locks, no further lock acquisition)
  • 22. Challenges have changed “At present [1981], the largest airlines and banks have about 10,000 terminals and about 100 active transactions at any instant. These transactions live for a second or two and are gone forever.” The Transaction Concept: Virtues and Limitations - http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
  • 23. MVCC • Readers don’t block writers and writers don’t block readers. • Writers block writers to prevent Dirty Writes.
  • 24. MVCC – Insert row (PostgreSQL)
  • 25. MVCC – Delete row (PostgreSQL)
  • 26. MVCC – Update row (PostgreSQL)
  • 27. MVCC • Two types of snapshots: • Query-level: Read Committed • Transaction-level: Snapshot Isolation • Watch out for long-running transactions
  • 28. Phenomena • The SQL-92 standard introduced three phenomena: • dirty read • non-repeatable read • phantom read. • In reality, there are more: • dirty write • read skew • write skew • lost update.
  • 38. SQL Standard Isolation Levels Isolation Level Dirty Read Non- Repeatable Read Phantom Read Read Uncommitted Yes Yes Yes Read Committed No Yes Yes Repeatable Read No No Yes Serializable No No No
  • 39. Oracle Isolation Levels Isolation Level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Committed No Yes Yes Yes Yes Yes Serializable No No No No Yes No
  • 40. SQL Server Isolation Levels Isolation level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Uncommitted Yes Yes Yes Yes Yes Yes Read Committed No Yes Yes Yes Yes Yes Repeatable Read No No Yes No No No Serializable No No No No No No Read Committed SI No Yes Yes Yes Yes Yes Snapshot Ioslation No No No No Yes No
  • 41. PostgreSQL Isolation Levels Isolation level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Uncommitted No Yes Yes Yes Yes Yes Read Committed No Yes Yes Yes Yes Yes Repeatable Read No No No No Yes No Serializable No No No No No No
  • 42. MySQL Isolation Levels Isolation level Dirty Read Non- Repeatable Read Phantom Read Read Skew Write Skew Lost Update Read Uncommitted Yes Yes Yes Yes Yes Yes Read Committed No Yes Yes Yes Yes Yes Repeatable Read No No No No Yes Yes Serializable No No No No No No
  • 43. Beyond ACID • ACID is not sufficient • What about multi-request logical transactions?
  • 46. Version-based optimistic locking @Version private int version; UPDATE post SET name = ‘Name’, version = 1 WHERE id = 1 AND version = 0
  • 52. Versionless optimistic locking @Entity @Table(name = "post") @DynamicUpdate @OptimisticLocking(type = OptimisticLockType.DIRTY) public class Post { @Id private Long id; private String title; private long views; private int likes; }
  • 54. Explicit optimistic locking modes Lock Mode Type Description NONE In the absence of explicit locking, the application will use implicit locking (optimistic or pessimistic) OPTIMISTIC Always issues a version check upon transaction commit, therefore ensuring optimistic locking repeatable reads. READ Same as OPTIMISTIC. OPTIMISTIC_FORCE_INCREMENT Always increases the entity version (even when the entity doesn’t change) and issues a version check upon transaction commit, therefore ensuring optimistic locking repeatable reads. WRITE Same as OPTIMISTIC_FORCE_INCREMENT. PESSIMISTIC_READ A shared lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_WRITE lock. PESSIMISTIC_WRITE An exclusive lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or a PESSIMISTIC_WRITE lock. PESSIMISTIC_FORCE_INCREMENT A database lock is acquired to prevent any other transaction from acquiring a PESSIMISTIC_READ or a PESSIMISTIC_WRITE lock and the entity version is incremented upon transaction commit.
  • 56. LockModeType.OPTIMISTIC_FORCE_INCREMENT Repository repository = entityManager.find(Repository.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); executeSync(() -> { doInJPA(_entityManager -> { Repository _repository = _entityManager.find(Repository.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); Commit _commit = new Commit(_repository); _commit.getChanges().add(new Change("Intro.md", "0a1,2...")); _entityManager.persist(_commit); }); }); Commit commit = new Commit(repository); commit.getChanges().add(new Change("FrontMatter.md", "0a1,5...")); commit.getChanges().add(new Change("HibernateIntro.md", "17c17...")); entityManager.persist(commit);