SlideShare a Scribd company logo
Distributed Transaction
Management in
Spring & JEE
Mushfekur Rahman
Senior Software Engineer
Transaction 101
● Need to perform multiple operations on a datasource for a particular
client action
● Need to make this action atomic
○ All or None
● Well... it cannot be that difficult
○ Obtain a connection
○ Start a transaction
○ Do your DB work
○ Commit the changes
2
But… Life’s Not *That* Easy
3
Transactions In The Grand Scheme
● Most of the functional real life application usually involves various
components (DBs, Message Brokers, IMDGs, EJBs etc.) *usually* running
in different machines and connected through a network
● We often need to make transactional operations involving multiple
resources
● The simple Local Transaction model doesn’t suffice anymore
● The necessity for something that can talk to and monitor all the resources
and perform transactions across all (e.g. Global Transaction management)
4
Hola Distributed Transaction Processing (DTP)
● Distributed Transaction accesses or modifies data stored in multiple
datasources
● A global Transaction Manager (TM) governs whether to commit or rollback
changes made in a distributed transaction
● A good application server should have this functionality out of the box
● But we have various application servers (WebLogic, WildFly, GlassFish)
running numerous applications each one having different transactional
needs and each one talking to their own data sources
● There has to be an open general specification to coordinate between a
TM and other involved components
5
X/Open XA Standard
● Specification to facilitate Distributed Transaction Processing (DTP) across
heterogenous components
● Guarantees Atomicity of a transaction among multiple components
using a 2-Phase Commit (2PC) protocol
● Describes the interface between a global transaction manager, data
sources and applications
● The Global Transaction Manager tracks the participants in the transaction
(i.e. XAResources), and works with them to carry out 2PC. XA TM is
separate from an application's interactions with servers. It maintains a log
of its decisions to commit or roll back, which it can use to recover in case
of a system outage.
6
X/Open XA Standard (Contd.)
7
Java Transaction API (JTA)
● Java Transaction API (JTA) is modelled on top of Open XA spec
● JTA Specifies standard Java interfaces between a transaction manager and
the parties involved in a distributed transaction system such as:
● Resource manager
○ Should implement javax.transaction.xa.XAResource for it to participate in a
distributed transaction
● Application server
○ Should implement javax.transaction.TransactionManager to manage
transactions on behalf of the application
● Transactional applications
○ Should implement javax.transaction.UserTransaction to specify transaction
boundaries of an action 8
Putting It Altogether
9
WebLogic Transaction Manager
● WebLogic application server provides DTP out of the box
● XA Resources willing to be managed by WL TM need to register
themselves to be managed during the server bootstrapping process
● TM then coordinates the transactions among the resources using 2PC
protocol of XA
● Provides monitoring tools to keep track of the health of transactional
resources
● Provides interface to tweak different transaction configurations
● Individual transactions can be monitored using OEM
10
WebLogic Transaction Manager (Contd.)
11
Transaction Boundary Demarcation
● Let’s re-iterate a little
○ Three JTA interfaces for DTP
■ XA Resources ✅
■ Transaction Manager ✅
■ Application Programs
● Application programs only need to mark transaction boundaries
● Boundary of a transaction can be set both:
○ Programmatically
○ Declaratively
12
Programmatic Transaction Management
● AKA Bean Managed Transaction
● You need to write manual code to demarcate the boundaries of
transaction
● Very little usage in Therap (e.g. backend-test)
● EJB
○ Application code can begin and end transaction through the
javax.transaction.UserTransaction interface
● Spring
○ Recommends using
org.springframework.transaction.support.TransactionTemplate
for programmatic transaction demarcation
13
Declarative Transaction Management
● AKA Container Managed Transaction (CMT)
● Convention over Configuration (yay! even less work for programmers)
● EJB
○ CMT in EJB environment is strictly tied to JTA
○ All Session Beans and MDBs may use CMT
○ Delegates the responsibility of starting and committing of a transaction
○ Can set transaction attributes using @TransactionAttribute annotation
○ Rollback occurs for any system exception (RTE) and not app exception
(checked exceptions)
● Spring
○ Need to configure DTM in context configuration
○ Need to set transaction boundaries and attributes using @Transactional
annotation in class and/or method level
14
Configure Declarative Transaction in Spring
<tx:jta-transaction-manager/>
Creates a default JtaTransactionManager bean with name "transactionManager",
matching the default bean name expected by <tx:annotation-driven/>.
Automatically detects WebLogic, WebSphere and OC4J: creating a
WebLogicJtaTransactionManager, WebSphereUowTransactionManager or
OC4JJtaTransactionManager, respectively.
<tx:annotation-driven/>
Indicates that transaction configuration is defined by annotations on bean classes, and
that proxies are automatically to be created for the relevant annotated beans.
15
Understanding @Transactional
● Marks scope of ongoing transaction and enabled by AOP proxies
● The combination of AOP with transactional metadata yields an AOP
proxy that uses a TransactionInterceptor in conjunction with an
appropriate PlatformTransactionManager implementation to drive
transactions around method invocations
N.B. Proxy is default mode but AspectJ is also an option
16
@Transactional Properties
The @Transactional annotation is metadata that specifies that an interface, class, or
method must have transactional semantics; for example, "start a brand new read-only
transaction when this method is invoked, suspending any existing transaction". The
default @Transactional settings are as follows:
● Propagation setting is PROPAGATION_REQUIRED
● Isolation level is ISOLATION_DEFAULT
● Transaction is read/write
● Transaction timeout defaults to the default timeout of the underlying transaction
system, or to none if timeouts are not supported
● Any RuntimeException triggers rollback, and any checked Exception does not
17
Did I Say Proxy?
● Classic structural design pattern
● A proxy acts as a substitute for a real service object used by a client and can
weave additional work (cross-cutting concerns) around the target service
○ Transaction Demarcation
○ Access Control
○ Caching etc.
● Spring AOP modes
○ Proxy (Runtime weaving)
○ AspectJ (Compile/Load-time weaving)
● Our choice: Proxy
○ Easier to configure
○ Less load-time overhead
18
Understanding Spring AOP Proxies
19
Calling Flow via AOP Proxy
20
@Transactional Documentation
When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do
annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the
annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you
need to annotate non-public methods.
...
Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional
annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface
(or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that
Java annotations are not inherited from interfaces means that if you are using class-based proxies ( proxy-target-
class="true") or the weaving-based aspect ( mode="aspectj"), then the transaction settings are not recognized by the
proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly
bad.
21
More from Doc
In proxy mode (which is the default), only external
method calls coming in through the proxy are
intercepted. This means that self-invocation, in effect, a
method within the target object calling another method
of the target object, will not lead to an actual transaction
at runtime even if the invoked method is marked with
@Transactional. Also, the proxy must be fully
initialized to provide the expected behaviour so you
should not rely on this feature in your initialization code,
i.e. @PostConstruct.
public class NotSoGreatService {
public void doSomething() {
// code
supposedToDoSomethingInTx();
}
@Transactional
public void supposedToDoSomethingInTx() {
// transactional code
}
} 22
@Transactional TL;DR
● In Proxy Mode
○ @Transactional on concrete class and public methods of concrete class
○ Methods are only intercepted through proxy for external calls so no self-
invocation
○ Proxy must be fully initialized before the expected functionality to work so no
usage inside constructor or bean construction callbacks (e.g.
@PostConstruct)
● In AspectJ Mode
○ “Reality can be anything I want.” - Thanos (Avengers: Infinity War)
23
How’d I Know If It’s Working?
● Don’t get fooled by the
simplicity of Declarative TM
● If you mess up demarcation, no
error is raised in runtime
● Verify, don’t just rely!
24
Step #1: Enable Logs
● Enable debug log for org.springframework.transaction and
additionally for org.springframework.orm.jpa in logback.xml
● First one is not mandatory to trace transactions but helps to relate with
EntityManager sessions
<logger name="org.springframework.orm.jpa" level="debug"/>
<logger name="org.springframework.transaction" level="debug"/>
25
Step #2: Tracing Through Logs
26
To Learn More
● Official Spring Documentation on Transaction Management
https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-
reference/html/transaction.html
● Java EE 7 Tutorial: Transactions
https://docs.oracle.com/javaee/7/tutorial/transactions.htm
● Fusion Middleware Programming JTA for Oracle WebLogic Server
https://docs.oracle.com/cd/E24329_01/web.1211/e24377/gstrx.htm#WLJTA11
5
27
Thanks!
@Transactional(rollbackFor = SorryItAllWentOverMyHeadException.class)
28

More Related Content

What's hot

ZON Dev Days 2013
ZON Dev Days 2013ZON Dev Days 2013
ZON Dev Days 2013
Miguel Hasse de Oliveira
 
Mongodb meetup
Mongodb meetupMongodb meetup
Mongodb meetup
Eytan Daniyalzade
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
Sergey Stupin
 
Observer pattern with Stl, boost and qt
Observer pattern with Stl, boost and qtObserver pattern with Stl, boost and qt
Observer pattern with Stl, boost and qt
Daniel Eriksson
 
Tools in action jdk mission control and flight recorder
Tools in action  jdk mission control and flight recorderTools in action  jdk mission control and flight recorder
Tools in action jdk mission control and flight recorder
Jean-Philippe BEMPEL
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
HDR1001
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
Asankhaya Sharma
 
RPC in Smalltalk
 RPC in Smalltalk RPC in Smalltalk
RPC in Smalltalk
ESUG
 
Omni ledger
Omni ledgerOmni ledger
Omni ledger
YongraeJo
 
Logitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket scienceLogitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket science
EDS Systems
 
jTransfo lightning talk
jTransfo lightning talkjTransfo lightning talk
jTransfo lightning talk
Joachim Van der Auwera
 
LCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS Roadmap
Linaro
 
Event Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQEvent Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQ
Luke Luo
 
Iot with-the-best & VSCP
Iot with-the-best & VSCPIot with-the-best & VSCP
Iot with-the-best & VSCP
Ake Hedman
 
Vft
VftVft
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactions
Ondrej Mihályi
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional Memory
Smruti Sarangi
 
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept ExploitsSemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
星曼 陈
 

What's hot (20)

ZON Dev Days 2013
ZON Dev Days 2013ZON Dev Days 2013
ZON Dev Days 2013
 
Mongodb meetup
Mongodb meetupMongodb meetup
Mongodb meetup
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
 
Observer pattern with Stl, boost and qt
Observer pattern with Stl, boost and qtObserver pattern with Stl, boost and qt
Observer pattern with Stl, boost and qt
 
Tools in action jdk mission control and flight recorder
Tools in action  jdk mission control and flight recorderTools in action  jdk mission control and flight recorder
Tools in action jdk mission control and flight recorder
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
 
RPC in Smalltalk
 RPC in Smalltalk RPC in Smalltalk
RPC in Smalltalk
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Omni ledger
Omni ledgerOmni ledger
Omni ledger
 
Logitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket scienceLogitoring - log-driven monitoring and the Rocket science
Logitoring - log-driven monitoring and the Rocket science
 
jTransfo lightning talk
jTransfo lightning talkjTransfo lightning talk
jTransfo lightning talk
 
LCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS Roadmap
 
Event Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQEvent Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQ
 
Iot with-the-best & VSCP
Iot with-the-best & VSCPIot with-the-best & VSCP
Iot with-the-best & VSCP
 
Vft
VftVft
Vft
 
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactions
 
Transactional Memory
Transactional MemoryTransactional Memory
Transactional Memory
 
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept ExploitsSemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
SemFuzz: Semantics-based Automatic Generation of Proof-of-Concept Exploits
 

Similar to Distributed Transaction Management in Spring & JEE

Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
Ye Win
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction ManagementUMA MAHESWARI
 
Transaction and concurrency pitfalls in Java
Transaction and concurrency pitfalls in JavaTransaction and concurrency pitfalls in Java
Transaction and concurrency pitfalls in Java
Ersen Öztoprak
 
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
GeeksLab Odessa
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
Rajeev Rastogi (KRR)
 
Java Distributed Transactions
Java Distributed TransactionsJava Distributed Transactions
Java Distributed Transactions
Anjana Fernando
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - TransactionsDmitry Buzdin
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
Ben Abdallah Helmi
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
Santosh Kumar Kar
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
OdessaJS Conf
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
Dmytro Sokolov
 
Microsoft Hekaton
Microsoft HekatonMicrosoft Hekaton
Microsoft Hekaton
Siraj Memon
 
Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"
Fwdays
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
Mydbops
 
MongoDB WiredTiger Internals: Journey To Transactions
  MongoDB WiredTiger Internals: Journey To Transactions  MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
M Malai
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
ElifTech
 
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Brian Brazil
 
MuleSoft Meetup: Transaction Management
MuleSoft Meetup: Transaction ManagementMuleSoft Meetup: Transaction Management
MuleSoft Meetup: Transaction Management
Pankaj Goyal
 
GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)
GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)
GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)
Apache Apex
 
Transaction states and properties
Transaction states and propertiesTransaction states and properties
Transaction states and properties
Chetan Mahawar
 

Similar to Distributed Transaction Management in Spring & JEE (20)

Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
 
Transaction and concurrency pitfalls in Java
Transaction and concurrency pitfalls in JavaTransaction and concurrency pitfalls in Java
Transaction and concurrency pitfalls in Java
 
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
 
Java Distributed Transactions
Java Distributed TransactionsJava Distributed Transactions
Java Distributed Transactions
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
 
Spring transaction part4
Spring transaction   part4Spring transaction   part4
Spring transaction part4
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
 
Microsoft Hekaton
Microsoft HekatonMicrosoft Hekaton
Microsoft Hekaton
 
Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
 
MongoDB WiredTiger Internals: Journey To Transactions
  MongoDB WiredTiger Internals: Journey To Transactions  MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
 
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
Monitoring Kubernetes with Prometheus (Kubernetes Ireland, 2016)
 
MuleSoft Meetup: Transaction Management
MuleSoft Meetup: Transaction ManagementMuleSoft Meetup: Transaction Management
MuleSoft Meetup: Transaction Management
 
GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)
GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)
GE IOT Predix Time Series & Data Ingestion Service using Apache Apex (Hadoop)
 
Transaction states and properties
Transaction states and propertiesTransaction states and properties
Transaction states and properties
 

Recently uploaded

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 

Recently uploaded (20)

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

Distributed Transaction Management in Spring & JEE

  • 1. Distributed Transaction Management in Spring & JEE Mushfekur Rahman Senior Software Engineer
  • 2. Transaction 101 ● Need to perform multiple operations on a datasource for a particular client action ● Need to make this action atomic ○ All or None ● Well... it cannot be that difficult ○ Obtain a connection ○ Start a transaction ○ Do your DB work ○ Commit the changes 2
  • 3. But… Life’s Not *That* Easy 3
  • 4. Transactions In The Grand Scheme ● Most of the functional real life application usually involves various components (DBs, Message Brokers, IMDGs, EJBs etc.) *usually* running in different machines and connected through a network ● We often need to make transactional operations involving multiple resources ● The simple Local Transaction model doesn’t suffice anymore ● The necessity for something that can talk to and monitor all the resources and perform transactions across all (e.g. Global Transaction management) 4
  • 5. Hola Distributed Transaction Processing (DTP) ● Distributed Transaction accesses or modifies data stored in multiple datasources ● A global Transaction Manager (TM) governs whether to commit or rollback changes made in a distributed transaction ● A good application server should have this functionality out of the box ● But we have various application servers (WebLogic, WildFly, GlassFish) running numerous applications each one having different transactional needs and each one talking to their own data sources ● There has to be an open general specification to coordinate between a TM and other involved components 5
  • 6. X/Open XA Standard ● Specification to facilitate Distributed Transaction Processing (DTP) across heterogenous components ● Guarantees Atomicity of a transaction among multiple components using a 2-Phase Commit (2PC) protocol ● Describes the interface between a global transaction manager, data sources and applications ● The Global Transaction Manager tracks the participants in the transaction (i.e. XAResources), and works with them to carry out 2PC. XA TM is separate from an application's interactions with servers. It maintains a log of its decisions to commit or roll back, which it can use to recover in case of a system outage. 6
  • 7. X/Open XA Standard (Contd.) 7
  • 8. Java Transaction API (JTA) ● Java Transaction API (JTA) is modelled on top of Open XA spec ● JTA Specifies standard Java interfaces between a transaction manager and the parties involved in a distributed transaction system such as: ● Resource manager ○ Should implement javax.transaction.xa.XAResource for it to participate in a distributed transaction ● Application server ○ Should implement javax.transaction.TransactionManager to manage transactions on behalf of the application ● Transactional applications ○ Should implement javax.transaction.UserTransaction to specify transaction boundaries of an action 8
  • 10. WebLogic Transaction Manager ● WebLogic application server provides DTP out of the box ● XA Resources willing to be managed by WL TM need to register themselves to be managed during the server bootstrapping process ● TM then coordinates the transactions among the resources using 2PC protocol of XA ● Provides monitoring tools to keep track of the health of transactional resources ● Provides interface to tweak different transaction configurations ● Individual transactions can be monitored using OEM 10
  • 12. Transaction Boundary Demarcation ● Let’s re-iterate a little ○ Three JTA interfaces for DTP ■ XA Resources ✅ ■ Transaction Manager ✅ ■ Application Programs ● Application programs only need to mark transaction boundaries ● Boundary of a transaction can be set both: ○ Programmatically ○ Declaratively 12
  • 13. Programmatic Transaction Management ● AKA Bean Managed Transaction ● You need to write manual code to demarcate the boundaries of transaction ● Very little usage in Therap (e.g. backend-test) ● EJB ○ Application code can begin and end transaction through the javax.transaction.UserTransaction interface ● Spring ○ Recommends using org.springframework.transaction.support.TransactionTemplate for programmatic transaction demarcation 13
  • 14. Declarative Transaction Management ● AKA Container Managed Transaction (CMT) ● Convention over Configuration (yay! even less work for programmers) ● EJB ○ CMT in EJB environment is strictly tied to JTA ○ All Session Beans and MDBs may use CMT ○ Delegates the responsibility of starting and committing of a transaction ○ Can set transaction attributes using @TransactionAttribute annotation ○ Rollback occurs for any system exception (RTE) and not app exception (checked exceptions) ● Spring ○ Need to configure DTM in context configuration ○ Need to set transaction boundaries and attributes using @Transactional annotation in class and/or method level 14
  • 15. Configure Declarative Transaction in Spring <tx:jta-transaction-manager/> Creates a default JtaTransactionManager bean with name "transactionManager", matching the default bean name expected by <tx:annotation-driven/>. Automatically detects WebLogic, WebSphere and OC4J: creating a WebLogicJtaTransactionManager, WebSphereUowTransactionManager or OC4JJtaTransactionManager, respectively. <tx:annotation-driven/> Indicates that transaction configuration is defined by annotations on bean classes, and that proxies are automatically to be created for the relevant annotated beans. 15
  • 16. Understanding @Transactional ● Marks scope of ongoing transaction and enabled by AOP proxies ● The combination of AOP with transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction with an appropriate PlatformTransactionManager implementation to drive transactions around method invocations N.B. Proxy is default mode but AspectJ is also an option 16
  • 17. @Transactional Properties The @Transactional annotation is metadata that specifies that an interface, class, or method must have transactional semantics; for example, "start a brand new read-only transaction when this method is invoked, suspending any existing transaction". The default @Transactional settings are as follows: ● Propagation setting is PROPAGATION_REQUIRED ● Isolation level is ISOLATION_DEFAULT ● Transaction is read/write ● Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported ● Any RuntimeException triggers rollback, and any checked Exception does not 17
  • 18. Did I Say Proxy? ● Classic structural design pattern ● A proxy acts as a substitute for a real service object used by a client and can weave additional work (cross-cutting concerns) around the target service ○ Transaction Demarcation ○ Access Control ○ Caching etc. ● Spring AOP modes ○ Proxy (Runtime weaving) ○ AspectJ (Compile/Load-time weaving) ● Our choice: Proxy ○ Easier to configure ○ Less load-time overhead 18
  • 20. Calling Flow via AOP Proxy 20
  • 21. @Transactional Documentation When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods. ... Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies ( proxy-target- class="true") or the weaving-based aspect ( mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad. 21
  • 22. More from Doc In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. @PostConstruct. public class NotSoGreatService { public void doSomething() { // code supposedToDoSomethingInTx(); } @Transactional public void supposedToDoSomethingInTx() { // transactional code } } 22
  • 23. @Transactional TL;DR ● In Proxy Mode ○ @Transactional on concrete class and public methods of concrete class ○ Methods are only intercepted through proxy for external calls so no self- invocation ○ Proxy must be fully initialized before the expected functionality to work so no usage inside constructor or bean construction callbacks (e.g. @PostConstruct) ● In AspectJ Mode ○ “Reality can be anything I want.” - Thanos (Avengers: Infinity War) 23
  • 24. How’d I Know If It’s Working? ● Don’t get fooled by the simplicity of Declarative TM ● If you mess up demarcation, no error is raised in runtime ● Verify, don’t just rely! 24
  • 25. Step #1: Enable Logs ● Enable debug log for org.springframework.transaction and additionally for org.springframework.orm.jpa in logback.xml ● First one is not mandatory to trace transactions but helps to relate with EntityManager sessions <logger name="org.springframework.orm.jpa" level="debug"/> <logger name="org.springframework.transaction" level="debug"/> 25
  • 26. Step #2: Tracing Through Logs 26
  • 27. To Learn More ● Official Spring Documentation on Transaction Management https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework- reference/html/transaction.html ● Java EE 7 Tutorial: Transactions https://docs.oracle.com/javaee/7/tutorial/transactions.htm ● Fusion Middleware Programming JTA for Oracle WebLogic Server https://docs.oracle.com/cd/E24329_01/web.1211/e24377/gstrx.htm#WLJTA11 5 27