SlideShare a Scribd company logo
TRANSACTIONS and
CONCURRENCY in JAVA
Ersen Öztoprak
Software Engineer at Iyzico, iyzicoder
hersenoztoprak@yahoo.com
https://www.linkedin.com/in/ersenoztoprak/
Agenda
 Examine transaction with ACID properties
 Transaction Management Models
 Local
 Programmatic
 Declerative
 Concurrency Management Essentials
 Drawbacks in concurrent transactions
 Isolation Levels in RDBMS
 Advices
Transaction?
 A transaction is a collection of read/write operations succeeding only if all
contained operations succeed.
 Executed Set of SQL commands as if it were all a single SQL statement
 In order to complete the transaction and commit all the changes, all the SQL
commands in the transaction must be succeeded
 Otherwise, all changes must be rollbacked and the database is returned to its
original state before the transaction started.
Why do we need it?
While sending money, what if
operation interrupt because
of corruption?
Money discounted from your
account, but not given
outside
Use of transaction
 The transaction block works with either all or no logic
 either all transactions are performed properly and accepted as valid
 Or at least one operation is failed before block ends, then no operation is
accepted
How to create and end a Transaction?
 To start a transaction:
 START TRANSACTION;
 BEGIN
 BEGIN WORK
 To end transaction:
 Commit(başarılı)
 Rollback(başarısız)
START TRANSACTION;
UPDATE account SET balance=balance+50 WHERE id = 1;
UPDATE account SET balance=balance-50 WHERE id = 2;
COMMIT;
transaction takes place
START TRANSACTION;
UPDATE account SET balance=balance+50 WHERE id = 1;
UPDATE account SET balance=balance-50 WHERE id = 2;
ROOLBACK;
nothing is done
Commands unable to rollback
 some sql commands(DDL) cannot be undone with rollback:
 CREATE DATABASE
 CREATE TABLE
 DROP DATABASE
 DROP TABLE
 ALTER TABLE
autocommit
 When activated(autocommit = 1), every single operation becomes a single
transaction
 unless a new transaction starts, all of the previous commands are traeated as a
transaction
 Set 0 to cancel
 When used, no need to specify start or begin tansaction explicitly:
SET AUTOCOMMIT=0;
UPDATE trans_test SET name=’a’ WHERE id=’1’;
COMMIT;
ACID
 All transactions share these properties: (represented by the acronym ACID)
 Atomicity : all-or-nothing
 Consistency : leave data in a consistent state(items cannot exist without an order)
 Isolation : must remain isolated from any other transaction
 Durability : committed state changes despite any failures afterwards
TRANSACTION MODELS
Threre are 3 types of transaction management model supported by Java:
 Local
 Programmatic
 Declarative
Local Transaction Model
 transactions are managed by the underlying database resource manager
 connections are managed rather than transactions.
 can't be used the when making database updates using an ORM framework
such as Hibernate, TopLink, or the JavaPersistence API
 but can be still applied when using DAO or JDBC-based frameworks and
database stored procedures
 The Local Transaction model is used in one of two ways:
 let the database manage the connection,
 manage the connection programmatically.
Let database manage
 set the autoCommit property on the JDBC Connection object to true (the
default value)
 which tells the underlying DBMS to commit the transaction after the insert,
update, or delete has completed, or roll back the work if it fails
manage the connection
programmatically
 set the autoCommit property on the Connection object to false which starts
the transaction
 manually commit or roll back the connection
 makes transaction active, JDBC waits to reflect changes until the end of the
transaction
 connection.commit() method reflects the changes
 connection.rollback() method
Transaction Management with JDBC
try{
DriverManager.registerDriver(newDriver());
connection= DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa","");
connection.setAutoCommit(false);
Statementstatement= connection.createStatement();
statement.executeUpdate("updateaccountsetbalance= balance- "+ amount+ "whereid = "+ sourceAccountId);
statement.executeUpdate("updateaccountsetbalance= balance+ "+ amount+ "whereid ="+ targetAccountId);
connection.commit();
} catch(SQLExceptione) {
connection.rollback();
}
Programmatic Transaction Model
 developer is responsible for managing the transaction
 unlike the Local Transaction model, you manage transactions and are
isolated from the underlying database connections
 the developer is responsible for
 obtaining a transaction from the transaction manager,
 starting the transaction,
 committing the transaction,
 ( if an exception occurs) rolling back the transaction.
Programmatic Transaction Management
In Spring
 Following are two approaches to programmatic transaction management:
 TransactionTemplate (recommended by Spring)
 PlatformTransactionManager (low level, similar to JDBC API)
TransactionTemplate
Based on Template Method Pattern such as:
try {
begin transaction
execute transactional code block
commit transaction
}
catch(Exception ex) {
rollback transaction
}
finally {
do resource clean up
}
Developer only need to provide the highlighted part
Template looks like…(pattern sample)
public abstractclassTransactionTemplate{
public finalvoidtransaction(){
try{
startTransaction();
doSomething();
commitTransaction();
}
catch(Exception e){
rollbackTransaction();
}
}
privatevoidstartTransaction(){…}
privatevoidcommitTransaction(){…}
privatevoidrollbackTransaction(){…}
abstractvoiddoSomething();
}
TransactionTemplate Sample
transactionTemplate.execute(newTransactionCallbackWithoutResult(){
@Override
protectedvoid doInTransactionWithoutResult(TransactionStatusstatus) {
AccountsourceAccount= accountDao.find(sourceAccountId);
AccounttargetAccount=accountDao.find(targetAccountId);
sourceAccount.setBalance(sourceAccount.getBalance()- amount);
targetAccount.setBalance(targetAccount.getBalance()+ amount);
accountDao.update(sourceAccount);
accountDao.update(targetAccount);
}
});
TransactionTemplate
Default transaction attributes can be manipulated as follows:
transactionTemplate.setTimeout(60);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transactionTemplate.setIsolationLevel(TransactionDefinition.
ISOLATION_REPEATABLE_READ);
TransactionTemplate rollback behaviour
 Performs rollback both on unchecked and checked exceptions
 Does not provide a mechanism for this purpose
PlatformTransactionManager
 Low – level approach
 Transaction begins and ends via calls to the PlatformTransactionManager API
 TransactionDefinition instance represents current transaction definition and
configurable as @Transaction annotation.Default values are same
 Commits and rollbacks are achieved by PlatformTransactionManager
PlatformTransactionManager sample
TransactionDefinitiondefinition=newDefaultTransactionDefinition();
TransactionStatusstatus= transactionManager.getTransaction(definition);
try{
Account sourceAccount=accountDao.find(sourceAccountId);
AccounttargetAccount= accountDao.find(targetAccountId);
sourceAccount.setBalance(sourceAccount.getBalance()- amount);
targetAccount.setBalance(targetAccount.getBalance()+amount);
accountDao.update(sourceAccount);
accountDao.update(targetAccount);
transactionManager.commit(status);
}catch (Exception e){
transactionManager.rollback(status);
}
PlatformTransactionManager types
TRANSACTION MANAGER CLASS DATA ACCESS TECHNOLOGY
DataSourceTransactionManager JDBC
JpaTransactionManager JPA - JDBC
HibernateTransactionManager Hibernate without JPA*, JDBC
JdoTransactionManager JDO(Java Data Objects**), JDBC
JtaTransactionManager Suitable for global transactions
(distributed transaction management)
* coding directly with Hibernate, use only its specific classes
(i.e. org.hibernate.*) and ways, and have no reference
to javax.persistence anywhere
** Java Data Objects is an API designed for persisting object-oriented data into
any database and provide a user-friendly query language using the Java syntax
Spring supports several implementations for different data accesss technologies:
Declarative Transaction
 Most common in Java platform
 handles much of the boilerplate code
 Let container takes care of starting, commiting and Rolling back the
transaction
 The developer is responsible only for specifying the transactions' behavior
 Runtime exceptions is rolled back by default
 If needed, developer must specify where and when to rollback a transaction
when a checked exception occurs
 In Spring, achieved by @Transactional annotation
 Thanks to AOP  (cross-cutting concern)
How Transactional Works?
 To understand backstage, we need to know proxy types:
 Dynamic proxy can only proxy by interface (so your target class needs to
implement an interface, which is then also implemented by the proxy class)
and compose target class
 CGLIB (and javassist) can create a proxy by subclassing. In this scenario the
proxy becomes a subclass of the target class. No need for interfaces.
Dynamic Proxy
Declerative Transaction By Dynamic
Proxy
CGLIB Proxy
Assume your bean looks like:
public class MyBean implements Bean {
@Override
public void write() {
//some write operations
}
}
Then the Dynamic Proxy looks like…
classMyProxyimplementsBean{
privateMyBeanbean;
@Override
public voidwrite(){
try{
startTransaction();
bean.write();
commitTransaction();
}
catch(Exception e) {
rollback();
}
}
}
@Transactional usage
@Transactional
public void transferMoney(long sourceAccountId,long targetAccountId,double amount) {
AccountsAccount = accountDao.find(sourceAccountId);
AccounttAccount = accountDao.find(targetAccountId);
sAccount.setBalance(sourceAccount.getBalance() -amount);
tAccount.setBalance(targetAccount.getBalance() + amount);
accountDao.update(sAccount);
accountDao.update(tAccount);
}
Properties of @Transactional
 propogation
 isolation(4.1 or above)
 readonly
 Time-out
 rollbackFor
 noRollbackFor
Propogation property
Isolation Property
 Defines the isolation level for current transaction at application level
 sets the current isolation level of the database by default
 Before using, be sure that, underlying database supports the specified
isolation level
 Values:
 DEFAULT
 READ_UNCOMMITTED
 READ_COMMITTED
 REPEATABLE_READ
 SERIALIZABLE
Read-only property
 false by default
 When set as true, Spring sets the JDBC transaction into a read-only mode
 By read-only transactions, an exception may be thrown while trying to
insert/update.(vendor dependent)
 make sense only on methods that start new transaction (with
propagation REQUIRED, REQUIRES_NEW).
 Read-only transactions can be a useful optimization in some cases, such as
when you are using Hibernate
Time-out Property
 in seconds
 How long this transaction runs before timing out and being rolled back
 defaults to the default timeout of the underlying transaction system
 Exclusively designed for use with REQUIRED or REQUIRES_NEW propogation
levels since they only applies to newly started transactions
RollbackFor – NoRollbackFor
 By default, the only way for rolling back of a transaction is throwing a
runtime exception
 If thrown exception is catched by the transaction owner, transaction is not
rolled back
 When throwing a checked exception, transaction is not rolled back by default
 rollbackFor property indicates which exception(subclass of throwable) types
must cause a transaction rollback.(even if exception is a checked exception)
 noRollbackFor property indicates which exception(subclass of throwable)
types must not cause a transaction rollback. (even if exception is a runtime
exception)
 If we don’t want to throw exception to rollback the exception below
command can be used:
 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Concurrency
 A RDBM must provide a runtime environment for multiple users working on
common data at the same time
 Access to the same resource at common times, may cause various drawbacks.
 These drawbacks are standardized as 4 main problems:
 Lost Update
 Dirty Read
 Non-repeatable read
 Phantom read
Lost Update
If the two transactions want to change the same columns, the second
transaction will overwrite the first one, therefore losing the first
transaction update.
Dirty Read
Dirty Read
 when a transaction is allowed to read the uncommitted changes of some
other concurrent transaction.
 When rolling back of uncommitted data, second transaction reads an invalid
value which is dangerous for applications
 most database systems offer a higher default isolation level
 Rarely needed.But may be useful in same cases:
 non-strict reporting queries
 batch processing task and you want to know its progress
Non-repeatable read
Non-repeatable read
 one transaction reads a database row without applying a shared(read) lock on
the newly fetched record, then a concurrent transaction might change this
row before the first transaction has ended.
 So during the course of a transaction, a row is retrieved twice and the values
within the row differ between reads.
Phantom read
Phantom read
 new rows are added by another transaction to the records being read
 is problematic when the current transaction makes a business decision based
on the first version of the given result set.
Non-repeatable read vs Phantom Read
 A non-repeatable read occurs, when during the course of a transaction, a row
is retrieved twice and the values within the row differ between reads.
 A phantom read occurs when, in the course of a transaction, two identical
queries are executed, and the collection of rows returned by the second
query is different from the first.
ISOLATION LEVELS
 Isolation Level determines how other transactions will behave in a transaction
against a transaction.
 weaker isolation level, more available operations but also more anomalies can
ocur
 higher isolation level, more consistent data, but also more deadlock and
lower scalalibity
 Mainly 4 types, from weaker to higher:
 READ_UNCOMMITTED
 READ_COMMITTED
 REPEATABLE_READ
 SERIALIZABLE
READ_UNCOMMITTED
 No isolation!
 A transaction can read uncommitted changes of other transactions
 Allows dirty reads
 The weakest blocking
 Dirty Read, Phantom read, non-repetable read may occour
 When uncomitted changes rollbacked, it may causes some consistency issues
 dirty read queries may be useful as long as you treat them as estimates and
don't make any critical decisions based upon them
READ_COMMITTED
 Transactions that are modified by other transactions but not committed
cannot be read.
 Guarantees that any data read was committed at the moment is read.
 Restricts the reader from seeing any intermediate, uncommitted, 'dirty' read.
 Makes no promise whatsoever that if the transaction re-issues the read, will
find the same data, data is free to change after it was read.
 Most of the database use this level as default
REPEATABLE_READ
 in addition to the guarantees of the read committed level, it also guarantees
that any data read cannot change
 if the transaction reads the same data again, it will find the previously read
data in place, unchanged, and available to read
SERIALIZABLE
 Highest isolation level
 Without a transaction ended, other transactions cannot Access the shared
resources.
 Naturally, in this case, concurrency problems are eliminated
ISOLATION LEVEL Capabilities
Isolation Level Dirty Read Non-repeatable Read Phantom Read
READ_UNCOMMITTED allowed allowed allowed
READ_COMMITTED prevented allowed allowed
REPEATABLE_READ prevented prevented allowed
SERIALIZABLE prevented prevented prevented
An example
• READ COMITTED, the second SELECT may return any data. A concurrent
transaction may update the record, delete it, insert new records. The second
select will always see the newdata.
• REPEATABLE READ the second SELECT is guaranteed to see the rows that has
seen at first select unchanged. New rows may be added by a concurrent
transaction in that one minute, but the existing rows cannot be deleted nor
changed
• SERIALIZABLE reads the second select is guaranteed to see exactly the same
rows as the first. No row can change, nor deleted, nor new rows could be
inserted by a concurrent transaction
To enable isolation
 We have two types of methods:
 Locking(Pessimistic)
 Row versioning (Optimistic)
Locking
 Resources are locked until end of the transaction
 Resources may be as:
 Row
 Rows
 table
 Most database systems locks 2 types of lock:
 shared (read)
 exclusive (write)
Isolation Levels and Locking
Level Lock Procedure
READ_UNCOMMITTED No lock
READ_COMMITTED Lock on committed data(read lock)
REPEATABLE_READ lock on block of sql(which is selected
by using select query – write lock)
SERIALIZABLE lock on full table
Optimistic Locking
 Done by addding a new column which holds version detail about row:
 write count of the row
 Write date of the row(last updated date)
 Before update the record, transaction can check value of the version column
 Then let the transaction commit if version is same, otherwise don’t
 But don’t forget setting the version column while updating
 Use @Version annotation for JPA
 No need to lock which seems as an advantage!
 Generated SQL command like below:
UPDATE TABLE SET ..., version = version + 1 WHERE id = ? AND version =
readVersion
General Advices
 Business needs should be well analyzed
 If the problem can be solved without writing code, may be with a unique-
index on the persistence layer, then it can be resolved
 The default isolation level of the database being studied should be known
 If the default isolation level does not meet the business need, the isolation
level can be manipulated on application level.Buth in this case don’t forget to
check if your database supports the manipulated isolation level
 Avoid to write to transactional and non-transactional environments in the
same operation as much as possible
 Limit the transaction block as much as you can, don’t include inquiry
operations and validations(availability)
Advices for @Transactional annotation
 should not be used on inquiry methods or single-write methods
 Meaningless on private methods(no proxy for private methods!)
 Meaningless for non-transactional environments(such as NOSQL databases)
 class based usage should be avoided
 Service layer is the best choice to use
 Don’t forget : Checked exceptions are not rolled back by default
 If spring bean is implemented from an interface, transactional method should
be overridden from interface(because of dynamic proxy)
Be careful while working with MYSQL!!!
 Mysql supports various storage engines.
 Storage engines are server elements which used to create and support
database tables
 With SHOW ENGINES; command, suportted list can be seen:
 MyISAM- DO NOT SUPPORTS TRANSACTIONS
 InnoDB and Falcon- SUPPORTS TRANSACTIONS
 While creating table, can be specified explicitly:
 CREATE TABLE t1 (i INT) ENGINE = INNODB;
Detailed at : https://www.w3resource.com/mysql/mysql-storage-engines.php
Transaction and concurrency pitfalls in Java

More Related Content

What's hot

Cooperative Wireless Communications
Cooperative Wireless CommunicationsCooperative Wireless Communications
Cooperative Wireless Communications
mravendi
 
Evolution of Wireless Communication Technologies
Evolution of Wireless Communication TechnologiesEvolution of Wireless Communication Technologies
Evolution of Wireless Communication Technologies
Akhil Bansal
 
Instalasi kabel UTP untuk jaringan komputer
Instalasi kabel UTP untuk jaringan komputerInstalasi kabel UTP untuk jaringan komputer
Instalasi kabel UTP untuk jaringan komputer
MULTIMEDIA 'n BROADCASTING SMKN 1 PUNGGING MOJOKERTO
 
Gsm presentation shaikot
Gsm presentation shaikotGsm presentation shaikot
Gsm presentation shaikot
sivakumar D
 
VLSI STEM Poster
VLSI STEM PosterVLSI STEM Poster
VLSI STEM Poster
Monique Harris
 
Instalasi jaringan komputer
Instalasi jaringan komputerInstalasi jaringan komputer
Instalasi jaringan komputer
RogerJulianto
 
Tugas makalah routing
Tugas makalah routingTugas makalah routing
Tugas makalah routing
esterina95
 
Fddi & Gigabit Ethernet
Fddi & Gigabit EthernetFddi & Gigabit Ethernet
Fddi & Gigabit Ethernet
Utkarsh Verma
 
Error Detection and Correction
Error Detection and Correction Error Detection and Correction
Error Detection and Correction
MdOsmanAzizMinaj
 
Teori Web Database Server Linux Debian
Teori Web Database Server Linux DebianTeori Web Database Server Linux Debian
Teori Web Database Server Linux Debian
Hasbullah Marwan
 
Fddi and isdn
Fddi and isdnFddi and isdn
Fddi and isdn
Vivek Jeena
 
Frequency Division Multiplexing Access (FDMA)
Frequency Division Multiplexing Access (FDMA)Frequency Division Multiplexing Access (FDMA)
Frequency Division Multiplexing Access (FDMA)
Soumen Santra
 
Data Communication & Computer network: Channel capacity
Data Communication & Computer network: Channel capacityData Communication & Computer network: Channel capacity
Data Communication & Computer network: Channel capacity
Dr Rajiv Srivastava
 
Snooping TCP
Snooping TCPSnooping TCP
Snooping TCP
Sushant Kushwaha
 
NETWORK LAYER - Logical Addressing
NETWORK LAYER - Logical AddressingNETWORK LAYER - Logical Addressing
NETWORK LAYER - Logical Addressing
Pankaj Debbarma
 
communication and network concepts
communication and network concepts communication and network concepts
communication and network concepts
Gunjan Mathur
 
Data communication
Data communicationData communication
Data communication
Muhammad Adeel Rajput
 
NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013
NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013
NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013
Amazon Web Services
 
IPv6 and IoT
IPv6 and IoTIPv6 and IoT
IPv6 and IoT
APNIC
 
Lte-m Sierra Wireless V1
Lte-m Sierra Wireless V1Lte-m Sierra Wireless V1
Lte-m Sierra Wireless V1
IoT Academy
 

What's hot (20)

Cooperative Wireless Communications
Cooperative Wireless CommunicationsCooperative Wireless Communications
Cooperative Wireless Communications
 
Evolution of Wireless Communication Technologies
Evolution of Wireless Communication TechnologiesEvolution of Wireless Communication Technologies
Evolution of Wireless Communication Technologies
 
Instalasi kabel UTP untuk jaringan komputer
Instalasi kabel UTP untuk jaringan komputerInstalasi kabel UTP untuk jaringan komputer
Instalasi kabel UTP untuk jaringan komputer
 
Gsm presentation shaikot
Gsm presentation shaikotGsm presentation shaikot
Gsm presentation shaikot
 
VLSI STEM Poster
VLSI STEM PosterVLSI STEM Poster
VLSI STEM Poster
 
Instalasi jaringan komputer
Instalasi jaringan komputerInstalasi jaringan komputer
Instalasi jaringan komputer
 
Tugas makalah routing
Tugas makalah routingTugas makalah routing
Tugas makalah routing
 
Fddi & Gigabit Ethernet
Fddi & Gigabit EthernetFddi & Gigabit Ethernet
Fddi & Gigabit Ethernet
 
Error Detection and Correction
Error Detection and Correction Error Detection and Correction
Error Detection and Correction
 
Teori Web Database Server Linux Debian
Teori Web Database Server Linux DebianTeori Web Database Server Linux Debian
Teori Web Database Server Linux Debian
 
Fddi and isdn
Fddi and isdnFddi and isdn
Fddi and isdn
 
Frequency Division Multiplexing Access (FDMA)
Frequency Division Multiplexing Access (FDMA)Frequency Division Multiplexing Access (FDMA)
Frequency Division Multiplexing Access (FDMA)
 
Data Communication & Computer network: Channel capacity
Data Communication & Computer network: Channel capacityData Communication & Computer network: Channel capacity
Data Communication & Computer network: Channel capacity
 
Snooping TCP
Snooping TCPSnooping TCP
Snooping TCP
 
NETWORK LAYER - Logical Addressing
NETWORK LAYER - Logical AddressingNETWORK LAYER - Logical Addressing
NETWORK LAYER - Logical Addressing
 
communication and network concepts
communication and network concepts communication and network concepts
communication and network concepts
 
Data communication
Data communicationData communication
Data communication
 
NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013
NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013
NFS and CIFS Options for AWS (STG401) | AWS re:Invent 2013
 
IPv6 and IoT
IPv6 and IoTIPv6 and IoT
IPv6 and IoT
 
Lte-m Sierra Wireless V1
Lte-m Sierra Wireless V1Lte-m Sierra Wireless V1
Lte-m Sierra Wireless V1
 

Similar to Transaction and concurrency pitfalls in Java

Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
UMA MAHESWARI
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
Ye Win
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
Dmitry Buzdin
 
Distributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEDistributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEE
Mushfekur Rahman
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction Management
Mark Ginnebaugh
 
Spring transaction management
Spring transaction managementSpring transaction management
Spring transaction management
Harshit Choudhary
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
Rajeev Rastogi (KRR)
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
Santosh Kumar Kar
 
Session 9 Tp9
Session 9 Tp9Session 9 Tp9
Session 9 Tp9
phanleson
 
MySQL Overview
MySQL OverviewMySQL Overview
MySQL Overview
Andrey Sidelev
 
Weblogic - overview of application server
Weblogic - overview of application serverWeblogic - overview of application server
Weblogic - overview of application server
Vibrant Technologies & Computers
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
Ben Abdallah Helmi
 
Transactions
TransactionsTransactions
Database Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyDatabase Transactions and SQL Server Concurrency
Database Transactions and SQL Server Concurrency
Boris Hristov
 
Java Distributed Transactions
Java Distributed TransactionsJava Distributed Transactions
Java Distributed Transactions
Anjana Fernando
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction Handling
Gaurav Arora
 
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
GeeksLab Odessa
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
Zohar Arad
 
Transaction
TransactionTransaction
Transaction
PratibhaRashmiSingh
 

Similar to Transaction and concurrency pitfalls in Java (20)

Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
 
Distributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEEDistributed Transaction Management in Spring & JEE
Distributed Transaction Management in Spring & JEE
 
SQL Server Transaction Management
SQL Server Transaction ManagementSQL Server Transaction Management
SQL Server Transaction Management
 
Spring transaction management
Spring transaction managementSpring transaction management
Spring transaction management
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
 
Session 9 Tp9
Session 9 Tp9Session 9 Tp9
Session 9 Tp9
 
MySQL Overview
MySQL OverviewMySQL Overview
MySQL Overview
 
Weblogic - overview of application server
Weblogic - overview of application serverWeblogic - overview of application server
Weblogic - overview of application server
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
 
Transactions
TransactionsTransactions
Transactions
 
Database Transactions and SQL Server Concurrency
Database Transactions and SQL Server ConcurrencyDatabase Transactions and SQL Server Concurrency
Database Transactions and SQL Server Concurrency
 
Java Distributed Transactions
Java Distributed TransactionsJava Distributed Transactions
Java Distributed Transactions
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction Handling
 
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
 
Transaction
TransactionTransaction
Transaction
 

Recently uploaded

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
seospiralmantra
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 

Recently uploaded (20)

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 

Transaction and concurrency pitfalls in Java

  • 1. TRANSACTIONS and CONCURRENCY in JAVA Ersen Öztoprak Software Engineer at Iyzico, iyzicoder hersenoztoprak@yahoo.com https://www.linkedin.com/in/ersenoztoprak/
  • 2. Agenda  Examine transaction with ACID properties  Transaction Management Models  Local  Programmatic  Declerative  Concurrency Management Essentials  Drawbacks in concurrent transactions  Isolation Levels in RDBMS  Advices
  • 3. Transaction?  A transaction is a collection of read/write operations succeeding only if all contained operations succeed.  Executed Set of SQL commands as if it were all a single SQL statement  In order to complete the transaction and commit all the changes, all the SQL commands in the transaction must be succeeded  Otherwise, all changes must be rollbacked and the database is returned to its original state before the transaction started.
  • 4. Why do we need it? While sending money, what if operation interrupt because of corruption? Money discounted from your account, but not given outside
  • 5. Use of transaction  The transaction block works with either all or no logic  either all transactions are performed properly and accepted as valid  Or at least one operation is failed before block ends, then no operation is accepted
  • 6. How to create and end a Transaction?  To start a transaction:  START TRANSACTION;  BEGIN  BEGIN WORK  To end transaction:  Commit(başarılı)  Rollback(başarısız)
  • 7. START TRANSACTION; UPDATE account SET balance=balance+50 WHERE id = 1; UPDATE account SET balance=balance-50 WHERE id = 2; COMMIT; transaction takes place START TRANSACTION; UPDATE account SET balance=balance+50 WHERE id = 1; UPDATE account SET balance=balance-50 WHERE id = 2; ROOLBACK; nothing is done
  • 8. Commands unable to rollback  some sql commands(DDL) cannot be undone with rollback:  CREATE DATABASE  CREATE TABLE  DROP DATABASE  DROP TABLE  ALTER TABLE
  • 9. autocommit  When activated(autocommit = 1), every single operation becomes a single transaction  unless a new transaction starts, all of the previous commands are traeated as a transaction  Set 0 to cancel  When used, no need to specify start or begin tansaction explicitly: SET AUTOCOMMIT=0; UPDATE trans_test SET name=’a’ WHERE id=’1’; COMMIT;
  • 10. ACID  All transactions share these properties: (represented by the acronym ACID)  Atomicity : all-or-nothing  Consistency : leave data in a consistent state(items cannot exist without an order)  Isolation : must remain isolated from any other transaction  Durability : committed state changes despite any failures afterwards
  • 11. TRANSACTION MODELS Threre are 3 types of transaction management model supported by Java:  Local  Programmatic  Declarative
  • 12. Local Transaction Model  transactions are managed by the underlying database resource manager  connections are managed rather than transactions.  can't be used the when making database updates using an ORM framework such as Hibernate, TopLink, or the JavaPersistence API  but can be still applied when using DAO or JDBC-based frameworks and database stored procedures  The Local Transaction model is used in one of two ways:  let the database manage the connection,  manage the connection programmatically.
  • 13. Let database manage  set the autoCommit property on the JDBC Connection object to true (the default value)  which tells the underlying DBMS to commit the transaction after the insert, update, or delete has completed, or roll back the work if it fails
  • 14. manage the connection programmatically  set the autoCommit property on the Connection object to false which starts the transaction  manually commit or roll back the connection  makes transaction active, JDBC waits to reflect changes until the end of the transaction  connection.commit() method reflects the changes  connection.rollback() method
  • 15. Transaction Management with JDBC try{ DriverManager.registerDriver(newDriver()); connection= DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa",""); connection.setAutoCommit(false); Statementstatement= connection.createStatement(); statement.executeUpdate("updateaccountsetbalance= balance- "+ amount+ "whereid = "+ sourceAccountId); statement.executeUpdate("updateaccountsetbalance= balance+ "+ amount+ "whereid ="+ targetAccountId); connection.commit(); } catch(SQLExceptione) { connection.rollback(); }
  • 16. Programmatic Transaction Model  developer is responsible for managing the transaction  unlike the Local Transaction model, you manage transactions and are isolated from the underlying database connections  the developer is responsible for  obtaining a transaction from the transaction manager,  starting the transaction,  committing the transaction,  ( if an exception occurs) rolling back the transaction.
  • 17. Programmatic Transaction Management In Spring  Following are two approaches to programmatic transaction management:  TransactionTemplate (recommended by Spring)  PlatformTransactionManager (low level, similar to JDBC API)
  • 18. TransactionTemplate Based on Template Method Pattern such as: try { begin transaction execute transactional code block commit transaction } catch(Exception ex) { rollback transaction } finally { do resource clean up } Developer only need to provide the highlighted part
  • 19. Template looks like…(pattern sample) public abstractclassTransactionTemplate{ public finalvoidtransaction(){ try{ startTransaction(); doSomething(); commitTransaction(); } catch(Exception e){ rollbackTransaction(); } } privatevoidstartTransaction(){…} privatevoidcommitTransaction(){…} privatevoidrollbackTransaction(){…} abstractvoiddoSomething(); }
  • 20. TransactionTemplate Sample transactionTemplate.execute(newTransactionCallbackWithoutResult(){ @Override protectedvoid doInTransactionWithoutResult(TransactionStatusstatus) { AccountsourceAccount= accountDao.find(sourceAccountId); AccounttargetAccount=accountDao.find(targetAccountId); sourceAccount.setBalance(sourceAccount.getBalance()- amount); targetAccount.setBalance(targetAccount.getBalance()+ amount); accountDao.update(sourceAccount); accountDao.update(targetAccount); } });
  • 21. TransactionTemplate Default transaction attributes can be manipulated as follows: transactionTemplate.setTimeout(60); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transactionTemplate.setIsolationLevel(TransactionDefinition. ISOLATION_REPEATABLE_READ);
  • 22. TransactionTemplate rollback behaviour  Performs rollback both on unchecked and checked exceptions  Does not provide a mechanism for this purpose
  • 23. PlatformTransactionManager  Low – level approach  Transaction begins and ends via calls to the PlatformTransactionManager API  TransactionDefinition instance represents current transaction definition and configurable as @Transaction annotation.Default values are same  Commits and rollbacks are achieved by PlatformTransactionManager
  • 24. PlatformTransactionManager sample TransactionDefinitiondefinition=newDefaultTransactionDefinition(); TransactionStatusstatus= transactionManager.getTransaction(definition); try{ Account sourceAccount=accountDao.find(sourceAccountId); AccounttargetAccount= accountDao.find(targetAccountId); sourceAccount.setBalance(sourceAccount.getBalance()- amount); targetAccount.setBalance(targetAccount.getBalance()+amount); accountDao.update(sourceAccount); accountDao.update(targetAccount); transactionManager.commit(status); }catch (Exception e){ transactionManager.rollback(status); }
  • 25. PlatformTransactionManager types TRANSACTION MANAGER CLASS DATA ACCESS TECHNOLOGY DataSourceTransactionManager JDBC JpaTransactionManager JPA - JDBC HibernateTransactionManager Hibernate without JPA*, JDBC JdoTransactionManager JDO(Java Data Objects**), JDBC JtaTransactionManager Suitable for global transactions (distributed transaction management) * coding directly with Hibernate, use only its specific classes (i.e. org.hibernate.*) and ways, and have no reference to javax.persistence anywhere ** Java Data Objects is an API designed for persisting object-oriented data into any database and provide a user-friendly query language using the Java syntax Spring supports several implementations for different data accesss technologies:
  • 26. Declarative Transaction  Most common in Java platform  handles much of the boilerplate code  Let container takes care of starting, commiting and Rolling back the transaction  The developer is responsible only for specifying the transactions' behavior  Runtime exceptions is rolled back by default  If needed, developer must specify where and when to rollback a transaction when a checked exception occurs  In Spring, achieved by @Transactional annotation  Thanks to AOP  (cross-cutting concern)
  • 27. How Transactional Works?  To understand backstage, we need to know proxy types:  Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which is then also implemented by the proxy class) and compose target class  CGLIB (and javassist) can create a proxy by subclassing. In this scenario the proxy becomes a subclass of the target class. No need for interfaces.
  • 29. Declerative Transaction By Dynamic Proxy
  • 31. Assume your bean looks like: public class MyBean implements Bean { @Override public void write() { //some write operations } }
  • 32. Then the Dynamic Proxy looks like… classMyProxyimplementsBean{ privateMyBeanbean; @Override public voidwrite(){ try{ startTransaction(); bean.write(); commitTransaction(); } catch(Exception e) { rollback(); } } }
  • 33. @Transactional usage @Transactional public void transferMoney(long sourceAccountId,long targetAccountId,double amount) { AccountsAccount = accountDao.find(sourceAccountId); AccounttAccount = accountDao.find(targetAccountId); sAccount.setBalance(sourceAccount.getBalance() -amount); tAccount.setBalance(targetAccount.getBalance() + amount); accountDao.update(sAccount); accountDao.update(tAccount); }
  • 34. Properties of @Transactional  propogation  isolation(4.1 or above)  readonly  Time-out  rollbackFor  noRollbackFor
  • 36. Isolation Property  Defines the isolation level for current transaction at application level  sets the current isolation level of the database by default  Before using, be sure that, underlying database supports the specified isolation level  Values:  DEFAULT  READ_UNCOMMITTED  READ_COMMITTED  REPEATABLE_READ  SERIALIZABLE
  • 37. Read-only property  false by default  When set as true, Spring sets the JDBC transaction into a read-only mode  By read-only transactions, an exception may be thrown while trying to insert/update.(vendor dependent)  make sense only on methods that start new transaction (with propagation REQUIRED, REQUIRES_NEW).  Read-only transactions can be a useful optimization in some cases, such as when you are using Hibernate
  • 38. Time-out Property  in seconds  How long this transaction runs before timing out and being rolled back  defaults to the default timeout of the underlying transaction system  Exclusively designed for use with REQUIRED or REQUIRES_NEW propogation levels since they only applies to newly started transactions
  • 39. RollbackFor – NoRollbackFor  By default, the only way for rolling back of a transaction is throwing a runtime exception  If thrown exception is catched by the transaction owner, transaction is not rolled back  When throwing a checked exception, transaction is not rolled back by default  rollbackFor property indicates which exception(subclass of throwable) types must cause a transaction rollback.(even if exception is a checked exception)  noRollbackFor property indicates which exception(subclass of throwable) types must not cause a transaction rollback. (even if exception is a runtime exception)  If we don’t want to throw exception to rollback the exception below command can be used:  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  • 40. Concurrency  A RDBM must provide a runtime environment for multiple users working on common data at the same time  Access to the same resource at common times, may cause various drawbacks.  These drawbacks are standardized as 4 main problems:  Lost Update  Dirty Read  Non-repeatable read  Phantom read
  • 41. Lost Update If the two transactions want to change the same columns, the second transaction will overwrite the first one, therefore losing the first transaction update.
  • 43. Dirty Read  when a transaction is allowed to read the uncommitted changes of some other concurrent transaction.  When rolling back of uncommitted data, second transaction reads an invalid value which is dangerous for applications  most database systems offer a higher default isolation level  Rarely needed.But may be useful in same cases:  non-strict reporting queries  batch processing task and you want to know its progress
  • 45. Non-repeatable read  one transaction reads a database row without applying a shared(read) lock on the newly fetched record, then a concurrent transaction might change this row before the first transaction has ended.  So during the course of a transaction, a row is retrieved twice and the values within the row differ between reads.
  • 47. Phantom read  new rows are added by another transaction to the records being read  is problematic when the current transaction makes a business decision based on the first version of the given result set.
  • 48. Non-repeatable read vs Phantom Read  A non-repeatable read occurs, when during the course of a transaction, a row is retrieved twice and the values within the row differ between reads.  A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.
  • 49. ISOLATION LEVELS  Isolation Level determines how other transactions will behave in a transaction against a transaction.  weaker isolation level, more available operations but also more anomalies can ocur  higher isolation level, more consistent data, but also more deadlock and lower scalalibity  Mainly 4 types, from weaker to higher:  READ_UNCOMMITTED  READ_COMMITTED  REPEATABLE_READ  SERIALIZABLE
  • 50. READ_UNCOMMITTED  No isolation!  A transaction can read uncommitted changes of other transactions  Allows dirty reads  The weakest blocking  Dirty Read, Phantom read, non-repetable read may occour  When uncomitted changes rollbacked, it may causes some consistency issues  dirty read queries may be useful as long as you treat them as estimates and don't make any critical decisions based upon them
  • 51. READ_COMMITTED  Transactions that are modified by other transactions but not committed cannot be read.  Guarantees that any data read was committed at the moment is read.  Restricts the reader from seeing any intermediate, uncommitted, 'dirty' read.  Makes no promise whatsoever that if the transaction re-issues the read, will find the same data, data is free to change after it was read.  Most of the database use this level as default
  • 52. REPEATABLE_READ  in addition to the guarantees of the read committed level, it also guarantees that any data read cannot change  if the transaction reads the same data again, it will find the previously read data in place, unchanged, and available to read
  • 53. SERIALIZABLE  Highest isolation level  Without a transaction ended, other transactions cannot Access the shared resources.  Naturally, in this case, concurrency problems are eliminated
  • 54. ISOLATION LEVEL Capabilities Isolation Level Dirty Read Non-repeatable Read Phantom Read READ_UNCOMMITTED allowed allowed allowed READ_COMMITTED prevented allowed allowed REPEATABLE_READ prevented prevented allowed SERIALIZABLE prevented prevented prevented
  • 55. An example • READ COMITTED, the second SELECT may return any data. A concurrent transaction may update the record, delete it, insert new records. The second select will always see the newdata. • REPEATABLE READ the second SELECT is guaranteed to see the rows that has seen at first select unchanged. New rows may be added by a concurrent transaction in that one minute, but the existing rows cannot be deleted nor changed • SERIALIZABLE reads the second select is guaranteed to see exactly the same rows as the first. No row can change, nor deleted, nor new rows could be inserted by a concurrent transaction
  • 56. To enable isolation  We have two types of methods:  Locking(Pessimistic)  Row versioning (Optimistic)
  • 57. Locking  Resources are locked until end of the transaction  Resources may be as:  Row  Rows  table  Most database systems locks 2 types of lock:  shared (read)  exclusive (write)
  • 58. Isolation Levels and Locking Level Lock Procedure READ_UNCOMMITTED No lock READ_COMMITTED Lock on committed data(read lock) REPEATABLE_READ lock on block of sql(which is selected by using select query – write lock) SERIALIZABLE lock on full table
  • 59. Optimistic Locking  Done by addding a new column which holds version detail about row:  write count of the row  Write date of the row(last updated date)  Before update the record, transaction can check value of the version column  Then let the transaction commit if version is same, otherwise don’t  But don’t forget setting the version column while updating  Use @Version annotation for JPA  No need to lock which seems as an advantage!  Generated SQL command like below: UPDATE TABLE SET ..., version = version + 1 WHERE id = ? AND version = readVersion
  • 60. General Advices  Business needs should be well analyzed  If the problem can be solved without writing code, may be with a unique- index on the persistence layer, then it can be resolved  The default isolation level of the database being studied should be known  If the default isolation level does not meet the business need, the isolation level can be manipulated on application level.Buth in this case don’t forget to check if your database supports the manipulated isolation level  Avoid to write to transactional and non-transactional environments in the same operation as much as possible  Limit the transaction block as much as you can, don’t include inquiry operations and validations(availability)
  • 61. Advices for @Transactional annotation  should not be used on inquiry methods or single-write methods  Meaningless on private methods(no proxy for private methods!)  Meaningless for non-transactional environments(such as NOSQL databases)  class based usage should be avoided  Service layer is the best choice to use  Don’t forget : Checked exceptions are not rolled back by default  If spring bean is implemented from an interface, transactional method should be overridden from interface(because of dynamic proxy)
  • 62. Be careful while working with MYSQL!!!  Mysql supports various storage engines.  Storage engines are server elements which used to create and support database tables  With SHOW ENGINES; command, suportted list can be seen:  MyISAM- DO NOT SUPPORTS TRANSACTIONS  InnoDB and Falcon- SUPPORTS TRANSACTIONS  While creating table, can be specified explicitly:  CREATE TABLE t1 (i INT) ENGINE = INNODB; Detailed at : https://www.w3resource.com/mysql/mysql-storage-engines.php