SlideShare a Scribd company logo
1 of 39
1CONFIDENTIAL
Database Transaction
Isolation and Locking in
Java
Kanstantsin Slisenka, Senior Software Engineer
EPAM Systems
Aug 25, 2016
2CONFIDENTIAL
About me
EXPERIENCE
INTERESTED IN
• Java backend developer
• Oracle Certified Java 7 Programmer, OCEWCD, OCEJPAD
• Speaker at Java tech talks
• Java backend, SOA, databases, integration frameworks
• Solution architecture
• High load, fault-tolerant, distributed, scalable systems
kanstantsin_slisenka@epam.com
github.com/kslisenko
www.slisenko.net
Kanstantsin Slisenka
3CONFIDENTIAL
DID YOU USE TX ISOLATION OR
LOCKING AT YOUR PROJECTS?
4CONFIDENTIAL
•Transaction phenomena and isolation levels
•Pessimistic and optimistic approaches
•Transaction isolation in MySQL
•Database-level locks in MySQL
•JPA features for locking
Agenda
5CONFIDENTIAL
WHAT IS DATABASE TRANSACTION?
6CONFIDENTIAL
Database transactions and ACID
Atomicity1
Consistency2
Isolation3
Durability4
7CONFIDENTIAL
• Problem of concurrent updates made
by parallel transactions
• No problem if no concurrent updates
• Databases have protection
Transaction phenomena
PROBLEM PHENOMENA
• Dirty read
• Non-repeatable read
• Phantom insert
8CONFIDENTIAL
Transaction phenomena: dirty read
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
DATABASES ARE
PROTECTED AGAINST
THIS IN REAL LIFE
~ not committed data
• Transactions can read not committed
(dirty) data of each other
• Other transaction rollbacks, decision
was made based on never existed
data
PROBLEM
9CONFIDENTIAL
• Transactions can read not committed
(dirty) data of each other
• Other transaction rollbacks, decision
was made based on never existed
data
Transaction phenomena: dirty read
PROBLEM
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
balance = 1100
customer balance
tom ~1100~
~ not committed data
DATABASES ARE
PROTECTED AGAINST
THIS IN REAL LIFE
10CONFIDENTIAL
• Transactions can read not committed
(dirty) data of each other
• Other transaction rollbacks, decision
was made based on never existed
data
Transaction phenomena: dirty read
PROBLEM
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
balance = 1100
read not
committed
balance = 1100
customer balance
tom ~1100~
customer balance
tom ~1100~
~ not committed data
DATABASES ARE
PROTECTED AGAINST
THIS IN REAL LIFE
11CONFIDENTIAL
• Transactions can read not committed
(dirty) data of each other
• Other transaction rollbacks, decision
was made based on never existed
data
Transaction phenomena: dirty read
PROBLEM
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
balance = 1100
read not
committed
balance = 1100
rollback
customer balance
tom ~1100~
customer balance
tom 1000
customer balance
tom ~1100~
~ not committed data
DATABASES ARE
PROTECTED AGAINST
THIS IN REAL LIFE
12CONFIDENTIAL
• One transaction updates data
• Other transaction reads data several
times and get different results
Transaction phenomena: non-repeatable read
PROBLEM
Transaction 1 Transaction 2customer balance
tom 1000
begin begin
WHEN WE CAN LIVE WITH THIS
• We are fine with not the most
recent data
~ not committed data
time
13CONFIDENTIAL
Transaction phenomena: non-repeatable read
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
read
balance = 1000
customer balance
tom 1000
~ not committed data
• One transaction updates data
• Other transaction reads data several
times and get different results
PROBLEM
WHEN WE CAN LIVE WITH THIS
• We are fine with not the most
recent data
14CONFIDENTIAL
Transaction phenomena: non-repeatable read
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
balance = 900
commit
read
balance = 1000
customer balance
tom 900
customer balance
tom 1000
~ not committed data
• One transaction updates data
• Other transaction reads data several
times and get different results
PROBLEM
WHEN WE CAN LIVE WITH THIS
• We are fine with not the most
recent data
15CONFIDENTIAL
Transaction phenomena: non-repeatable read
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
read
balance = 1000
customer balance
tom 900
customer balance
tom 1000
~ not committed data
customer balance
tom 900
read
balance = 900
balance = 900
commit
• One transaction updates data
• Other transaction reads data several
times and get different results
PROBLEM
WHEN WE CAN LIVE WITH THIS
• We are fine with not the most
recent data
16CONFIDENTIAL
• One transaction inserts/deletes rows
• Other transaction reads several
times and get different number of
rows
Transaction phenomena: phantom
PROBLEM
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
WHEN WE CAN LIVE WITH THIS
• Read single rows, not ranges
• We are fine with not the most recent
data
~ not committed data
17CONFIDENTIAL
Transaction phenomena: phantom
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
get all customers
where balance < 2000
got 1 record
customer balance
tom 1000
~ not committed data
• One transaction inserts/deletes rows
• Other transaction reads several
times and get different number of
rows
PROBLEM
WHEN WE CAN LIVE WITH THIS
• Read single rows, not ranges
• We are fine with not the most recent
data
18CONFIDENTIAL
Transaction phenomena: phantom
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
get all customers
where balance < 2000
got 1 record
customer balance
tom 1000
jerry 500
customer balance
tom 1000
insert new customer
commit
~ not committed data
• One transaction inserts/deletes rows
• Other transaction reads several
times and get different number of
rows
PROBLEM
WHEN WE CAN LIVE WITH THIS
• Read single rows, not ranges
• We are fine with not the most recent
data
19CONFIDENTIAL
Transaction phenomena: phantom
Transaction 1 Transaction 2customer balance
tom 1000
time
begin begin
get all customers
where balance < 2000
got 1 record
customer balance
tom 1000
jerry 500
customer balance
tom 1000
insert new customer
commit
customer balance
tom 1000
jerry 500
get all customers
where balance < 2000
got 2 records
~ not committed data
• One transaction inserts/deletes rows
• Other transaction reads several
times and get different number of
rows
PROBLEM
WHEN WE CAN LIVE WITH THIS
• Read single rows, not ranges
• We are fine with not the most recent
data
20CONFIDENTIAL
HOW TO PROTECT?
21CONFIDENTIAL
Transaction isolation levels (standard)
• ISO/IEC 9075:1992
• Information technology --
Database languages -- SQL
http://www.contrib.andrew.cmu.edu/~shadow/s
ql/sql1992.txt
READ
UNCOMMITED
READ
COMMITED
REPEATABLE
READ
SERIALIZABLE
Dirty read YES NO NO NO
Non-
repeatable
read
YES YES NO NO
Phantom YES YES YES NO
• Defined in SQL92
• Trade-off between performance, scalability and data protection
• Same work performed with the same inputs may result in
different answers, depending on isolation level
• Implementation can be VERY DIFFERNT in different databases
22CONFIDENTIAL
HOW DOES IT WORK?
IN DIFFERENT DATABASES
23CONFIDENTIAL
• Locking rows or ranges
• Like ReadWriteLock/synchronized in Java
• Concurrent transactions wait until lock is released
Optimistic and pessimistic approaches
PESSIMISTIC OPTIMISTIC
• Multi version concurrency control (MVCC)
• Doesn’t lock anything
• Save all versions of data
• We work with data snapshots
• Like GIT/SVN
24CONFIDENTIAL
• Shared lock – read lock, many owners
• Exclusive lock – write lock, one owner
Pessimistic locking
BY OWNERSHIP
range lock row lock user balance
tom 1000
jerry 1500
EXCLUSIVE
T1
SHARED
EXCLUSIVE SHARED
EXCLUSIVE SHARED
• Row - specific rows by index (if index exists)
• Range – all records by condition
range lock row lock user balance
tom 1000
jerry 1500
EXCLUSIVE
T1
SHARED
EXCLUSIVE SHARED
EXCLUSIVE SHARED
range lock row lock user balance
tom 1000
jerry 1500
EXCLUSIVET1
SHARED
EXCLUSIVE SHARED
EXCLUSIVE SHARED
BY SCOPE
T2
T2
range lock row lock user balance
tom 1000
jerry 1500
EXCLUSIVE
T1
SHARED
EXCLUSIVE SHARED
EXCLUSIVE SHARED
T2T3
T2
T3
25CONFIDENTIAL
Optimistic multi version concurrency control (MVCC)
Updated user balance Deleted
0 tom 1000
1 tom 1000
1100
2
Transaction 1 (TS=0) READ
Transaction 2 (TS=1) WRITE
• Transactions see the rows with version less or equal to transaction start time
• On update: new version is added
• On remove: deleted column is set of new version number
HOW IT WORKS
Transaction 3 (TS=2)
DELETE
26CONFIDENTIAL
Optimistic MVCC vs pessimistic locks
MVCC (OPTIMISTIC) LOCKS (PESSIMISTIC)
Behavior
1. Each transaction works with
it’s own version
2. Concurrent transaction fails
1. Transaction which owns lock
works with data
2. Concurrent transactions wait
Locks NO YES
Performance and
scalability
GOOD BAD
Deadlocks NO POSSIBLE
Guarantee of recent data
version
NO YES
Extra disk space needed YES NO
Durability
better (because
of saved versions)
27CONFIDENTIAL
DB CONCEPT
READ
UNCOMMITED
READ COMMITED REPEATABLE READ SERIALIZABLE SPECIFICS
Oracle MVCC
NOT
SUPPORTED
DEFAULT
return new snapshot
each read
NOT SUPPORTED
returns
snapshot of
data at
beginning of
transaction
+ READ ONLY LEVEL
transaction only sees data at the moment
of start, writes not allowed
always returns snapshots, transaction fail
when concurrent update
MySQL
(InnoDB)
MVCC
return new snapshot
each time
DEFAULT
- save snapshot at first
read
- return it for next reads
- locks ranges
- transaction
lifetime
- Shared lock
on select
MSSQL LOCKS
+ Double read
phenomena:
able to read
same row twice
while it is
migrating to
another place
on disk
SNAPSHOT
(optimistic)
- locks rows
- transaction lifetime
- locks ranges
- transaction
lifetime
- selects:
shared range
lock
- updates:
exclusive lock
+ SNAPSHOT LEVEL
- save snapshot at first read
- return it for next reads
- transactions fail in case of optimistic
lock concurrent update
return new snapshot
each time
LOCK (pessimistic)
DEFAULT
- locks rows
- statements
lifetime
PostgreSQL MVCC
NOT
SUPPORTED
DEFAULT
return new snapshot
each read
- save snapshot at first
read
- return it for next reads
predicate
locking
(optimistic)
always returns snapshots, transaction fail
when concurrent update
Transaction isolation levels in different databases
28CONFIDENTIAL
LIVE DEMO
TRANSACTION ISOLATION IN MYSQL
29CONFIDENTIAL
LOCK SPECIFIC OBJECTS!
WANT TO OPTIMIZE?
30CONFIDENTIAL
• SELECT … LOCK IN SHARE MODE – shared (read) lock
• SELECT … FOR UPDATE – exclusive (write) lock
Pessimistic locking of specific rows/ranges (MySQL)
LOCKING SELECTS
IDEA
• Increase isolation level for specific rows/ranges
• Other rows/ranges can have lower isolation level
31CONFIDENTIAL
LIVE DEMO
MYSQL PESSIMISTIC LOCKING OF SPECIFIC OBJECTS
32CONFIDENTIAL
Database deadlocks
row locks user balance
tom 1000
jerry 1500
Transaction 1
EXCLUSIVE
SHAREDEXCLUSIVE
SHARED
Transaction 2
Database deadlocks happen because of bad application architecture design
• Take locks in same order in every transaction
• Use as small as possible transactions
HOW TO PREVENT DEADLOCKS
33CONFIDENTIAL
WHAT ABOUT JAVA?
34CONFIDENTIAL
hibernate.connection.isolation=level
Transaction isolation: configuration in Java
JDBC
Hibernate
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/testdb?user=test&password=pass");
c.setTransactionIsolation(level);
Connection.TRANSACTION_NONE 0
Connection.TRANSACTION_READ_UNCOMMITED 1
Connection.TRANSACTION_READ_COMMITED 2
Connection.TRANSACTION_REPEATABLE_READ 4
Connection.TRANSACTION_SERIALIZABLE 8
35CONFIDENTIAL
JPA features for locking
Enum LockModeType
PESSIMISTIC_READ Shared lock
PESSIMISTIC_WRITE Exclusive lock
EntityManager
lock(Object entity, LockModeType
lockMode)
Makes additional locking select query just to
lock entity
find(Class<T> entityClass, Object
primaryKey, LockModeType lockMode)
Makes locking select when reading entity
refresh(Object entity, LockModeType
lockMode)
Makes locking select when reloading entity
NamedQuery
@NamedQuery(name=“myQuery”, query=“…”,
lockMode=LockModeType.PESSIMISTIC_READ)
Allows to specify that we need locking select
to any query
• Complex to manually lock
entity relationships
• @NamedQuery is only way to
specify query lock
ADVANTAGES
• It is really simple
• Database specific things are
hidden from developer
• Supports parent-child entities
DRAWBACKS
36CONFIDENTIAL
Transaction isolation and locking with JPA
• Repeatable reads because of EntityManager’s cache
• Requests do not always go to database
Behavior = EntityManager + 2’nd lvl cache + database
Database
user balance
tom 1000
jerry 1500
2’nd level cache
user balance
tom 900
EntityManager
1’st level cache
user balance
tom ~1100~CLIENT
APPLICATION
37CONFIDENTIAL
Conclusion
• Do you have problems because of concurrent updates?
– Same as concurrent programming in Java
– Sometimes we can allow phenomena
• Transaction Isolation is trade-off between data protection and performance
• Two main approaches in databases implementation:
– Optimistic: no locks, data is versioned
– Pessimistic: range and low locks
• JPA
– Simplifies usage of pessimistic locking
– Adds own specific behavior because of caches
• For better performance:
– Prefer smaller transactions: they hold long time locks and can make deadlocks
– Be careful with declarative transaction management it can make heavy transactions
38CONFIDENTIAL
Oracle
Chapter 2-4
References
MySQL
Chapter 1
JPA
Chapter 12,
Locking
MSSQL
Chapter 13
PostgreSQL
Chapter 10
Examples
https://github.com/
kslisenko/tx-isolation
39CONFIDENTIAL
QUESTIONS?
THANK YOU!
kanstantsin_slisenka@epam.com

More Related Content

What's hot

Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...Databricks
 
NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기Hoyoung Choi
 
Fully Utilizing Spark for Data Validation
Fully Utilizing Spark for Data ValidationFully Utilizing Spark for Data Validation
Fully Utilizing Spark for Data ValidationDatabricks
 
Spark SQL Join Improvement at Facebook
Spark SQL Join Improvement at FacebookSpark SQL Join Improvement at Facebook
Spark SQL Join Improvement at FacebookDatabricks
 
Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...
Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...
Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...Databricks
 
On Improving Broadcast Joins in Apache Spark SQL
On Improving Broadcast Joins in Apache Spark SQLOn Improving Broadcast Joins in Apache Spark SQL
On Improving Broadcast Joins in Apache Spark SQLDatabricks
 
Understanding and Improving Code Generation
Understanding and Improving Code GenerationUnderstanding and Improving Code Generation
Understanding and Improving Code GenerationDatabricks
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaEdureka!
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance TuningJeremy Leisy
 
Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?Yaroslav Tkachenko
 
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...Databricks
 
State of the Trino Project
State of the Trino ProjectState of the Trino Project
State of the Trino ProjectMartin Traverso
 
Storing State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your AnalyticsStoring State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your AnalyticsYaroslav Tkachenko
 
MongoDB at Scale
MongoDB at ScaleMongoDB at Scale
MongoDB at ScaleMongoDB
 
The Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesThe Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesDatabricks
 
LockFree Algorithm
LockFree AlgorithmLockFree Algorithm
LockFree AlgorithmMerry Merry
 
Spark shuffle introduction
Spark shuffle introductionSpark shuffle introduction
Spark shuffle introductioncolorant
 
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...Concord
 

What's hot (20)

Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
Deep Dive into Spark SQL with Advanced Performance Tuning with Xiao Li & Wenc...
 
NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기
 
Fully Utilizing Spark for Data Validation
Fully Utilizing Spark for Data ValidationFully Utilizing Spark for Data Validation
Fully Utilizing Spark for Data Validation
 
Spark SQL Join Improvement at Facebook
Spark SQL Join Improvement at FacebookSpark SQL Join Improvement at Facebook
Spark SQL Join Improvement at Facebook
 
Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...
Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...
Improving SparkSQL Performance by 30%: How We Optimize Parquet Pushdown and P...
 
On Improving Broadcast Joins in Apache Spark SQL
On Improving Broadcast Joins in Apache Spark SQLOn Improving Broadcast Joins in Apache Spark SQL
On Improving Broadcast Joins in Apache Spark SQL
 
Understanding and Improving Code Generation
Understanding and Improving Code GenerationUnderstanding and Improving Code Generation
Understanding and Improving Code Generation
 
PostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | EdurekaPostgreSQL Tutorial for Beginners | Edureka
PostgreSQL Tutorial for Beginners | Edureka
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
DOIって何?(図書館総合展2012版)
DOIって何?(図書館総合展2012版)DOIって何?(図書館総合展2012版)
DOIって何?(図書館総合展2012版)
 
Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?Streaming SQL for Data Engineers: The Next Big Thing?
Streaming SQL for Data Engineers: The Next Big Thing?
 
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
 
TBB 소개
TBB 소개TBB 소개
TBB 소개
 
State of the Trino Project
State of the Trino ProjectState of the Trino Project
State of the Trino Project
 
Storing State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your AnalyticsStoring State Forever: Why It Can Be Good For Your Analytics
Storing State Forever: Why It Can Be Good For Your Analytics
 
MongoDB at Scale
MongoDB at ScaleMongoDB at Scale
MongoDB at Scale
 
The Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization OpportunitiesThe Parquet Format and Performance Optimization Opportunities
The Parquet Format and Performance Optimization Opportunities
 
LockFree Algorithm
LockFree AlgorithmLockFree Algorithm
LockFree Algorithm
 
Spark shuffle introduction
Spark shuffle introductionSpark shuffle introduction
Spark shuffle introduction
 
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
Concord: Simple & Flexible Stream Processing on Apache Mesos: Data By The Bay...
 

Similar to Database transaction isolation and locking in Java

Why & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to queryWhy & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to queryAntonios Chatzipavlis
 
Navigating Transactions: ACID Complexity in Modern Databases
Navigating Transactions: ACID Complexity in Modern DatabasesNavigating Transactions: ACID Complexity in Modern Databases
Navigating Transactions: ACID Complexity in Modern DatabasesShivji Kumar Jha
 
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...Mydbops
 
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and LockingGeek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and LockingIDERA Software
 
Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...
Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...
Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...Rajesh Kannan S
 
Transaction concurrency control
Transaction concurrency controlTransaction concurrency control
Transaction concurrency controlAnand Grewal
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!Boris Hristov
 
Data Integrity in Java Applications (JFall 2013)
Data Integrity in Java Applications (JFall 2013)Data Integrity in Java Applications (JFall 2013)
Data Integrity in Java Applications (JFall 2013)Lucas Jellema
 
Respond to and troubleshoot production incidents like an sa
Respond to and troubleshoot production incidents like an saRespond to and troubleshoot production incidents like an sa
Respond to and troubleshoot production incidents like an saTom Cudd
 
Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...
Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...
Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...Clustrix
 
MySQL replication best practices 105-232-931
MySQL replication best practices 105-232-931MySQL replication best practices 105-232-931
MySQL replication best practices 105-232-931Baruch Osoveskiy
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwoashish61_scs
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwoashish61_scs
 
LeanXcale Presentation - Waterloo University
LeanXcale Presentation - Waterloo UniversityLeanXcale Presentation - Waterloo University
LeanXcale Presentation - Waterloo UniversityRicardo Jimenez-Peris
 
Events in a microservices architecture
Events in a microservices architectureEvents in a microservices architecture
Events in a microservices architectureSaul Caganoff
 

Similar to Database transaction isolation and locking in Java (20)

Why & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to queryWhy & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to query
 
Lec08
Lec08Lec08
Lec08
 
Transaction
TransactionTransaction
Transaction
 
Navigating Transactions: ACID Complexity in Modern Databases
Navigating Transactions: ACID Complexity in Modern DatabasesNavigating Transactions: ACID Complexity in Modern Databases
Navigating Transactions: ACID Complexity in Modern Databases
 
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
 
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and LockingGeek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
Geek Sync | How to Detect, Analyze, and Minimize SQL Server Blocking and Locking
 
Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...
Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...
Slashn Talk OLTP in Supply Chain - Handling Super-scale and Change Propagatio...
 
Transaction concurrency control
Transaction concurrency controlTransaction concurrency control
Transaction concurrency control
 
The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!The Nightmare of Locking, Blocking and Isolation Levels!
The Nightmare of Locking, Blocking and Isolation Levels!
 
Rails DB migrate SAFE.pdf
Rails DB migrate SAFE.pdfRails DB migrate SAFE.pdf
Rails DB migrate SAFE.pdf
 
Unit 5 dbms
Unit 5 dbmsUnit 5 dbms
Unit 5 dbms
 
J-Fall2013- Lucas Jellema: Integrity in Java apps handouts
J-Fall2013- Lucas Jellema: Integrity in Java apps handoutsJ-Fall2013- Lucas Jellema: Integrity in Java apps handouts
J-Fall2013- Lucas Jellema: Integrity in Java apps handouts
 
Data Integrity in Java Applications (JFall 2013)
Data Integrity in Java Applications (JFall 2013)Data Integrity in Java Applications (JFall 2013)
Data Integrity in Java Applications (JFall 2013)
 
Respond to and troubleshoot production incidents like an sa
Respond to and troubleshoot production incidents like an saRespond to and troubleshoot production incidents like an sa
Respond to and troubleshoot production incidents like an sa
 
Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...
Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...
Tech Talk Series, Part 4: How do you achieve high availability in a MySQL env...
 
MySQL replication best practices 105-232-931
MySQL replication best practices 105-232-931MySQL replication best practices 105-232-931
MySQL replication best practices 105-232-931
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwo
 
7 concurrency controltwo
7 concurrency controltwo7 concurrency controltwo
7 concurrency controltwo
 
LeanXcale Presentation - Waterloo University
LeanXcale Presentation - Waterloo UniversityLeanXcale Presentation - Waterloo University
LeanXcale Presentation - Waterloo University
 
Events in a microservices architecture
Events in a microservices architectureEvents in a microservices architecture
Events in a microservices architecture
 

More from Constantine Slisenka

Unlocking the secrets of successful architects: what skills and traits do you...
Unlocking the secrets of successful architects: what skills and traits do you...Unlocking the secrets of successful architects: what skills and traits do you...
Unlocking the secrets of successful architects: what skills and traits do you...Constantine Slisenka
 
Lyft talks #4 Orchestrating big data and ML pipelines at Lyft
Lyft talks #4 Orchestrating big data and ML pipelines at LyftLyft talks #4 Orchestrating big data and ML pipelines at Lyft
Lyft talks #4 Orchestrating big data and ML pipelines at LyftConstantine Slisenka
 
What does it take to be architect (for Cjicago JUG)
What does it take to be architect (for Cjicago JUG)What does it take to be architect (for Cjicago JUG)
What does it take to be architect (for Cjicago JUG)Constantine Slisenka
 
What does it take to be an architect
What does it take to be an architectWhat does it take to be an architect
What does it take to be an architectConstantine Slisenka
 
VoxxedDays Minsk - Building scalable WebSocket backend
VoxxedDays Minsk - Building scalable WebSocket backendVoxxedDays Minsk - Building scalable WebSocket backend
VoxxedDays Minsk - Building scalable WebSocket backendConstantine Slisenka
 
Building scalable web socket backend
Building scalable web socket backendBuilding scalable web socket backend
Building scalable web socket backendConstantine Slisenka
 
Latency tracing in distributed Java applications
Latency tracing in distributed Java applicationsLatency tracing in distributed Java applications
Latency tracing in distributed Java applicationsConstantine Slisenka
 
Distributed transactions in SOA and Microservices
Distributed transactions in SOA and MicroservicesDistributed transactions in SOA and Microservices
Distributed transactions in SOA and MicroservicesConstantine Slisenka
 
Best practices of building data streaming API
Best practices of building data streaming APIBest practices of building data streaming API
Best practices of building data streaming APIConstantine Slisenka
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and NettyConstantine Slisenka
 
Profiling distributed Java applications
Profiling distributed Java applicationsProfiling distributed Java applications
Profiling distributed Java applicationsConstantine Slisenka
 

More from Constantine Slisenka (11)

Unlocking the secrets of successful architects: what skills and traits do you...
Unlocking the secrets of successful architects: what skills and traits do you...Unlocking the secrets of successful architects: what skills and traits do you...
Unlocking the secrets of successful architects: what skills and traits do you...
 
Lyft talks #4 Orchestrating big data and ML pipelines at Lyft
Lyft talks #4 Orchestrating big data and ML pipelines at LyftLyft talks #4 Orchestrating big data and ML pipelines at Lyft
Lyft talks #4 Orchestrating big data and ML pipelines at Lyft
 
What does it take to be architect (for Cjicago JUG)
What does it take to be architect (for Cjicago JUG)What does it take to be architect (for Cjicago JUG)
What does it take to be architect (for Cjicago JUG)
 
What does it take to be an architect
What does it take to be an architectWhat does it take to be an architect
What does it take to be an architect
 
VoxxedDays Minsk - Building scalable WebSocket backend
VoxxedDays Minsk - Building scalable WebSocket backendVoxxedDays Minsk - Building scalable WebSocket backend
VoxxedDays Minsk - Building scalable WebSocket backend
 
Building scalable web socket backend
Building scalable web socket backendBuilding scalable web socket backend
Building scalable web socket backend
 
Latency tracing in distributed Java applications
Latency tracing in distributed Java applicationsLatency tracing in distributed Java applications
Latency tracing in distributed Java applications
 
Distributed transactions in SOA and Microservices
Distributed transactions in SOA and MicroservicesDistributed transactions in SOA and Microservices
Distributed transactions in SOA and Microservices
 
Best practices of building data streaming API
Best practices of building data streaming APIBest practices of building data streaming API
Best practices of building data streaming API
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Profiling distributed Java applications
Profiling distributed Java applicationsProfiling distributed Java applications
Profiling distributed Java applications
 

Recently uploaded

PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 

Recently uploaded (20)

PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 

Database transaction isolation and locking in Java

  • 1. 1CONFIDENTIAL Database Transaction Isolation and Locking in Java Kanstantsin Slisenka, Senior Software Engineer EPAM Systems Aug 25, 2016
  • 2. 2CONFIDENTIAL About me EXPERIENCE INTERESTED IN • Java backend developer • Oracle Certified Java 7 Programmer, OCEWCD, OCEJPAD • Speaker at Java tech talks • Java backend, SOA, databases, integration frameworks • Solution architecture • High load, fault-tolerant, distributed, scalable systems kanstantsin_slisenka@epam.com github.com/kslisenko www.slisenko.net Kanstantsin Slisenka
  • 3. 3CONFIDENTIAL DID YOU USE TX ISOLATION OR LOCKING AT YOUR PROJECTS?
  • 4. 4CONFIDENTIAL •Transaction phenomena and isolation levels •Pessimistic and optimistic approaches •Transaction isolation in MySQL •Database-level locks in MySQL •JPA features for locking Agenda
  • 6. 6CONFIDENTIAL Database transactions and ACID Atomicity1 Consistency2 Isolation3 Durability4
  • 7. 7CONFIDENTIAL • Problem of concurrent updates made by parallel transactions • No problem if no concurrent updates • Databases have protection Transaction phenomena PROBLEM PHENOMENA • Dirty read • Non-repeatable read • Phantom insert
  • 8. 8CONFIDENTIAL Transaction phenomena: dirty read Transaction 1 Transaction 2customer balance tom 1000 time begin begin DATABASES ARE PROTECTED AGAINST THIS IN REAL LIFE ~ not committed data • Transactions can read not committed (dirty) data of each other • Other transaction rollbacks, decision was made based on never existed data PROBLEM
  • 9. 9CONFIDENTIAL • Transactions can read not committed (dirty) data of each other • Other transaction rollbacks, decision was made based on never existed data Transaction phenomena: dirty read PROBLEM Transaction 1 Transaction 2customer balance tom 1000 time begin begin balance = 1100 customer balance tom ~1100~ ~ not committed data DATABASES ARE PROTECTED AGAINST THIS IN REAL LIFE
  • 10. 10CONFIDENTIAL • Transactions can read not committed (dirty) data of each other • Other transaction rollbacks, decision was made based on never existed data Transaction phenomena: dirty read PROBLEM Transaction 1 Transaction 2customer balance tom 1000 time begin begin balance = 1100 read not committed balance = 1100 customer balance tom ~1100~ customer balance tom ~1100~ ~ not committed data DATABASES ARE PROTECTED AGAINST THIS IN REAL LIFE
  • 11. 11CONFIDENTIAL • Transactions can read not committed (dirty) data of each other • Other transaction rollbacks, decision was made based on never existed data Transaction phenomena: dirty read PROBLEM Transaction 1 Transaction 2customer balance tom 1000 time begin begin balance = 1100 read not committed balance = 1100 rollback customer balance tom ~1100~ customer balance tom 1000 customer balance tom ~1100~ ~ not committed data DATABASES ARE PROTECTED AGAINST THIS IN REAL LIFE
  • 12. 12CONFIDENTIAL • One transaction updates data • Other transaction reads data several times and get different results Transaction phenomena: non-repeatable read PROBLEM Transaction 1 Transaction 2customer balance tom 1000 begin begin WHEN WE CAN LIVE WITH THIS • We are fine with not the most recent data ~ not committed data time
  • 13. 13CONFIDENTIAL Transaction phenomena: non-repeatable read Transaction 1 Transaction 2customer balance tom 1000 time begin begin read balance = 1000 customer balance tom 1000 ~ not committed data • One transaction updates data • Other transaction reads data several times and get different results PROBLEM WHEN WE CAN LIVE WITH THIS • We are fine with not the most recent data
  • 14. 14CONFIDENTIAL Transaction phenomena: non-repeatable read Transaction 1 Transaction 2customer balance tom 1000 time begin begin balance = 900 commit read balance = 1000 customer balance tom 900 customer balance tom 1000 ~ not committed data • One transaction updates data • Other transaction reads data several times and get different results PROBLEM WHEN WE CAN LIVE WITH THIS • We are fine with not the most recent data
  • 15. 15CONFIDENTIAL Transaction phenomena: non-repeatable read Transaction 1 Transaction 2customer balance tom 1000 time begin begin read balance = 1000 customer balance tom 900 customer balance tom 1000 ~ not committed data customer balance tom 900 read balance = 900 balance = 900 commit • One transaction updates data • Other transaction reads data several times and get different results PROBLEM WHEN WE CAN LIVE WITH THIS • We are fine with not the most recent data
  • 16. 16CONFIDENTIAL • One transaction inserts/deletes rows • Other transaction reads several times and get different number of rows Transaction phenomena: phantom PROBLEM Transaction 1 Transaction 2customer balance tom 1000 time begin begin WHEN WE CAN LIVE WITH THIS • Read single rows, not ranges • We are fine with not the most recent data ~ not committed data
  • 17. 17CONFIDENTIAL Transaction phenomena: phantom Transaction 1 Transaction 2customer balance tom 1000 time begin begin get all customers where balance < 2000 got 1 record customer balance tom 1000 ~ not committed data • One transaction inserts/deletes rows • Other transaction reads several times and get different number of rows PROBLEM WHEN WE CAN LIVE WITH THIS • Read single rows, not ranges • We are fine with not the most recent data
  • 18. 18CONFIDENTIAL Transaction phenomena: phantom Transaction 1 Transaction 2customer balance tom 1000 time begin begin get all customers where balance < 2000 got 1 record customer balance tom 1000 jerry 500 customer balance tom 1000 insert new customer commit ~ not committed data • One transaction inserts/deletes rows • Other transaction reads several times and get different number of rows PROBLEM WHEN WE CAN LIVE WITH THIS • Read single rows, not ranges • We are fine with not the most recent data
  • 19. 19CONFIDENTIAL Transaction phenomena: phantom Transaction 1 Transaction 2customer balance tom 1000 time begin begin get all customers where balance < 2000 got 1 record customer balance tom 1000 jerry 500 customer balance tom 1000 insert new customer commit customer balance tom 1000 jerry 500 get all customers where balance < 2000 got 2 records ~ not committed data • One transaction inserts/deletes rows • Other transaction reads several times and get different number of rows PROBLEM WHEN WE CAN LIVE WITH THIS • Read single rows, not ranges • We are fine with not the most recent data
  • 21. 21CONFIDENTIAL Transaction isolation levels (standard) • ISO/IEC 9075:1992 • Information technology -- Database languages -- SQL http://www.contrib.andrew.cmu.edu/~shadow/s ql/sql1992.txt READ UNCOMMITED READ COMMITED REPEATABLE READ SERIALIZABLE Dirty read YES NO NO NO Non- repeatable read YES YES NO NO Phantom YES YES YES NO • Defined in SQL92 • Trade-off between performance, scalability and data protection • Same work performed with the same inputs may result in different answers, depending on isolation level • Implementation can be VERY DIFFERNT in different databases
  • 22. 22CONFIDENTIAL HOW DOES IT WORK? IN DIFFERENT DATABASES
  • 23. 23CONFIDENTIAL • Locking rows or ranges • Like ReadWriteLock/synchronized in Java • Concurrent transactions wait until lock is released Optimistic and pessimistic approaches PESSIMISTIC OPTIMISTIC • Multi version concurrency control (MVCC) • Doesn’t lock anything • Save all versions of data • We work with data snapshots • Like GIT/SVN
  • 24. 24CONFIDENTIAL • Shared lock – read lock, many owners • Exclusive lock – write lock, one owner Pessimistic locking BY OWNERSHIP range lock row lock user balance tom 1000 jerry 1500 EXCLUSIVE T1 SHARED EXCLUSIVE SHARED EXCLUSIVE SHARED • Row - specific rows by index (if index exists) • Range – all records by condition range lock row lock user balance tom 1000 jerry 1500 EXCLUSIVE T1 SHARED EXCLUSIVE SHARED EXCLUSIVE SHARED range lock row lock user balance tom 1000 jerry 1500 EXCLUSIVET1 SHARED EXCLUSIVE SHARED EXCLUSIVE SHARED BY SCOPE T2 T2 range lock row lock user balance tom 1000 jerry 1500 EXCLUSIVE T1 SHARED EXCLUSIVE SHARED EXCLUSIVE SHARED T2T3 T2 T3
  • 25. 25CONFIDENTIAL Optimistic multi version concurrency control (MVCC) Updated user balance Deleted 0 tom 1000 1 tom 1000 1100 2 Transaction 1 (TS=0) READ Transaction 2 (TS=1) WRITE • Transactions see the rows with version less or equal to transaction start time • On update: new version is added • On remove: deleted column is set of new version number HOW IT WORKS Transaction 3 (TS=2) DELETE
  • 26. 26CONFIDENTIAL Optimistic MVCC vs pessimistic locks MVCC (OPTIMISTIC) LOCKS (PESSIMISTIC) Behavior 1. Each transaction works with it’s own version 2. Concurrent transaction fails 1. Transaction which owns lock works with data 2. Concurrent transactions wait Locks NO YES Performance and scalability GOOD BAD Deadlocks NO POSSIBLE Guarantee of recent data version NO YES Extra disk space needed YES NO Durability better (because of saved versions)
  • 27. 27CONFIDENTIAL DB CONCEPT READ UNCOMMITED READ COMMITED REPEATABLE READ SERIALIZABLE SPECIFICS Oracle MVCC NOT SUPPORTED DEFAULT return new snapshot each read NOT SUPPORTED returns snapshot of data at beginning of transaction + READ ONLY LEVEL transaction only sees data at the moment of start, writes not allowed always returns snapshots, transaction fail when concurrent update MySQL (InnoDB) MVCC return new snapshot each time DEFAULT - save snapshot at first read - return it for next reads - locks ranges - transaction lifetime - Shared lock on select MSSQL LOCKS + Double read phenomena: able to read same row twice while it is migrating to another place on disk SNAPSHOT (optimistic) - locks rows - transaction lifetime - locks ranges - transaction lifetime - selects: shared range lock - updates: exclusive lock + SNAPSHOT LEVEL - save snapshot at first read - return it for next reads - transactions fail in case of optimistic lock concurrent update return new snapshot each time LOCK (pessimistic) DEFAULT - locks rows - statements lifetime PostgreSQL MVCC NOT SUPPORTED DEFAULT return new snapshot each read - save snapshot at first read - return it for next reads predicate locking (optimistic) always returns snapshots, transaction fail when concurrent update Transaction isolation levels in different databases
  • 30. 30CONFIDENTIAL • SELECT … LOCK IN SHARE MODE – shared (read) lock • SELECT … FOR UPDATE – exclusive (write) lock Pessimistic locking of specific rows/ranges (MySQL) LOCKING SELECTS IDEA • Increase isolation level for specific rows/ranges • Other rows/ranges can have lower isolation level
  • 31. 31CONFIDENTIAL LIVE DEMO MYSQL PESSIMISTIC LOCKING OF SPECIFIC OBJECTS
  • 32. 32CONFIDENTIAL Database deadlocks row locks user balance tom 1000 jerry 1500 Transaction 1 EXCLUSIVE SHAREDEXCLUSIVE SHARED Transaction 2 Database deadlocks happen because of bad application architecture design • Take locks in same order in every transaction • Use as small as possible transactions HOW TO PREVENT DEADLOCKS
  • 34. 34CONFIDENTIAL hibernate.connection.isolation=level Transaction isolation: configuration in Java JDBC Hibernate Connection c = DriverManager.getConnection("jdbc:mysql://localhost/testdb?user=test&password=pass"); c.setTransactionIsolation(level); Connection.TRANSACTION_NONE 0 Connection.TRANSACTION_READ_UNCOMMITED 1 Connection.TRANSACTION_READ_COMMITED 2 Connection.TRANSACTION_REPEATABLE_READ 4 Connection.TRANSACTION_SERIALIZABLE 8
  • 35. 35CONFIDENTIAL JPA features for locking Enum LockModeType PESSIMISTIC_READ Shared lock PESSIMISTIC_WRITE Exclusive lock EntityManager lock(Object entity, LockModeType lockMode) Makes additional locking select query just to lock entity find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) Makes locking select when reading entity refresh(Object entity, LockModeType lockMode) Makes locking select when reloading entity NamedQuery @NamedQuery(name=“myQuery”, query=“…”, lockMode=LockModeType.PESSIMISTIC_READ) Allows to specify that we need locking select to any query • Complex to manually lock entity relationships • @NamedQuery is only way to specify query lock ADVANTAGES • It is really simple • Database specific things are hidden from developer • Supports parent-child entities DRAWBACKS
  • 36. 36CONFIDENTIAL Transaction isolation and locking with JPA • Repeatable reads because of EntityManager’s cache • Requests do not always go to database Behavior = EntityManager + 2’nd lvl cache + database Database user balance tom 1000 jerry 1500 2’nd level cache user balance tom 900 EntityManager 1’st level cache user balance tom ~1100~CLIENT APPLICATION
  • 37. 37CONFIDENTIAL Conclusion • Do you have problems because of concurrent updates? – Same as concurrent programming in Java – Sometimes we can allow phenomena • Transaction Isolation is trade-off between data protection and performance • Two main approaches in databases implementation: – Optimistic: no locks, data is versioned – Pessimistic: range and low locks • JPA – Simplifies usage of pessimistic locking – Adds own specific behavior because of caches • For better performance: – Prefer smaller transactions: they hold long time locks and can make deadlocks – Be careful with declarative transaction management it can make heavy transactions
  • 38. 38CONFIDENTIAL Oracle Chapter 2-4 References MySQL Chapter 1 JPA Chapter 12, Locking MSSQL Chapter 13 PostgreSQL Chapter 10 Examples https://github.com/ kslisenko/tx-isolation