SlideShare ist ein Scribd-Unternehmen logo
1 von 28
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

Weitere ähnliche Inhalte

Was ist angesagt?

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overviewSergey 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 qtDaniel 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 recorderJean-Philippe BEMPEL
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresHDR1001
 
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 LanguageAsankhaya Sharma
 
RPC in Smalltalk
 RPC in Smalltalk RPC in Smalltalk
RPC in SmalltalkESUG
 
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 scienceEDS Systems
 
LCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLCA13: Common Clk Framework DVFS Roadmap
LCA13: Common Clk Framework DVFS RoadmapLinaro
 
Event Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQEvent Driven with LibUV and ZeroMQ
Event Driven with LibUV and ZeroMQLuke Luo
 
Iot with-the-best & VSCP
Iot with-the-best & VSCPIot with-the-best & VSCP
Iot with-the-best & VSCPAke Hedman
 
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactionsOndrej Mihályi
 
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星曼 陈
 

Was ist angesagt? (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
 

Ähnlich wie Distributed Transaction Management in Spring & JEE

Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction ManagementYe 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 JavaErsen Öztoprak
 
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...
Java/Scala Lab 2016. Дмитрий Соколов: Принципы работы с транзакциями при помо...GeeksLab Odessa
 
Java Distributed Transactions
Java Distributed TransactionsJava Distributed Transactions
Java Distributed TransactionsAnjana Fernando
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - TransactionsDmitry Buzdin
 
'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'2020OdessaJS 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 HekatonSiraj 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 TransactionsMydbops
 
MongoDB WiredTiger Internals: Journey To Transactions
  MongoDB WiredTiger Internals: Journey To Transactions  MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsM Malai
 
Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic PatternsElifTech
 
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 ManagementPankaj 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 propertiesChetan Mahawar
 

Ähnlich wie 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
 

Kürzlich hochgeladen

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 

Kürzlich hochgeladen (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 

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