Upload
alyssa-pugh
View
235
Download
3
Tags:
Embed Size (px)
Citation preview
Training and consulting in Java, EJB, J2EE, and XML
[email protected] / http://www.middleware-company.com
Mastering Transactions
Performing atomic, consistent, isolated, and durable operations using
Java and EJB
© The Middleware Company • http://www.middleware-company.com 2
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 3
Transactions Motivation
Client Object Client Object Client Object
Server ObjectServer Object
Database Database
Discussion point: What issues might arise in a database in a multi-tier deployment?
© The Middleware Company • http://www.middleware-company.com 4
Discussion point: If we get an RMI RemoteException, did the server complete its processing correctly?
Transactions Motivation (cont)
© The Middleware Company • http://www.middleware-company.com 5
Notice the following code:
try {// Withdraw funds from account 1
}catch (Exception e) {
// If an error occurred, do not proceed.
return;}try {
// Otherwise, deposit funds into account 2}catch (Exception e) {
// If an error occurred, do not proceed,// and redeposit the funds back into account 1.
return;}
Discussion point: What’s wrong with this code?
Transactions Motivation (cont)
© The Middleware Company • http://www.middleware-company.com 6
Transactions Motivation (cont)
Conclusions We are not getting enough information about what really
is happening Checking lots of 'corner cases' is error prone Exception handling is not enough
We want determinism The very idea of putting ‘undo’ logic in clients is bad That undo logic should be pushed to the server.
© The Middleware Company • http://www.middleware-company.com 7
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 8
Transactions and the ACID Properties
As we have seen, exceptions are not enough for enterprise computing Code is non-deterministic
Transactions guarantee determinism Transactions give you four virtues, called the ACID
properties: Atomicity Consistency Isolation Durability
Discussion points: Have you used transactions in your past projects? If so, how did you use them?
© The Middleware Company • http://www.middleware-company.com 9
Atomicity ACID Property
"All or nothing" operations You get atomicity from the database
It undoes updates automatically upon failure
Example: Withdraw from one bank, deposit into another Want both or neither to succeed Database will undo deposit or withdraw if either fails
© The Middleware Company • http://www.middleware-company.com 10
Consistency ACID Property
System is always consistent based upon state invariants But: You don't get consistency for free!
Transactions give you an opportunity to write code that checks the system state. Example: You can write bean code that throws an
exception if balance is < 0.
© The Middleware Company • http://www.middleware-company.com 11
Isolation ACID Property
Operations on shared data are isolated. When a transaction begins, your 'umbrella' opens.
Now you have an isolated, tunnel view of the database
When the transaction ends, your 'umbrella' closes You are no longer safe.
You choose how isolated you are from others Challenge: balance safety and concurrency.
Safety Concurrency
© The Middleware Company • http://www.middleware-company.com 12
Durability ACID Property
Catastrophic failure is recoverable. If a database crashes, it will reboot and fix itself
automatically.
© The Middleware Company • http://www.middleware-company.com 13
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 14
Flat transactions
Flat transactions are the most common transaction type Supported by all databases Only transaction type supported universally by EJB
© The Middleware Company • http://www.middleware-company.com 15
Nested transactions
Unit of work nested in other unit of work Motivation: Trip-planning problem
1) You buy a ticket from NYC to Los Angeles
2) You buy a ticket from Los Angeles to Japan
3) You buy a ticket from Japan to London, but the flight is booked.
Under a flat transaction, this would cause a rollback of all tickets purchased.
But: We might not want this! What if we chose another airline?
Nested transactions allow us to retry nested units of work. But: What if the nested unit of work cannot be made to succeed? Then ultimately the outer unit of work will fail.
© The Middleware Company • http://www.middleware-company.com 16
Nested transactions
© The Middleware Company • http://www.middleware-company.com 17
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 18
Transaction Boundaries
Transaction boundaries mark the beginning and end of transactions
Analogy is an umbrella When you open the umbrella, you’re protected from the rain When you close the umbrella, you’re vulnerable again
It’s up to you to choose the right boundaries Transaction is too long? Concurrency decreases due to collisions
with other transactions Transaction is too short? Won’t encapsulate your atomic
operations 3 Ways to control transactional boundaries:
Inside your bean programmatically Inside your bean declaratively From client code
© The Middleware Company • http://www.middleware-company.com 19
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 20
OTS, JTS, and JTA
Motivation: Need an API to start and end transactions EJB/J2EE transaction control dates back to CORBA days
Control CORBA transactions via the Object Transaction Service (OTS)
Sun took the Java mapping of OTS and split it into two parts: JTS: Interfaces that make any database work with any transaction
service JTA: Enables you to control when transactions begin and end
The takeaway point: Vendors care about JTS. We care only about JTA.
© The Middleware Company • http://www.middleware-company.com 21
The UserTransaction interface
You should only care about one JTA interface, UserTransaction:
interface javax.transaction.UserTransaction {public abstract void begin();public abstract void commit();public abstract void rollback();public abstract void setRollbackOnly();public abstract int getStatus();public abstract void setTransactionTimeout(int);
}
interface javax.transaction.Status {public static final int STATUS_ACTIVE;public static final int STATUS_MARKED_ROLLBACK;public static final int STATUS_PREPARED;public static final int STATUS_COMMITTED;public static final int STATUS_ROLLEDBACK;public static final int STATUS_UNKNOWN;public static final int STATUS_NO_TRANSACTION;public static final int STATUS_PREPARING;public static final int STATUS_COMMITTING;public static final int STATUS_ROLLING_BACK;
}
© The Middleware Company • http://www.middleware-company.com 22
Looking up the UserTransaction interface
The JTA UserTransaction interface is actually an interface to the application server’s transaction manager
It’s the public API that the transaction manager exposes The app server is responsible for publishing this interface to you To get a reference to this, you need to lookup the interface via JNDI
Just like you use JNDI to lookup EJB homes, JDBC drivers, etc. Application server must publish JTA under
"java:comp/UserTransaction" Note that weblogic violates this Code that works with weblogic:Context ctx = new InitialContext(...);
javax.transaction.UserTransaction userTran =(javax.transaction.UserTransaction)PortableRemoteObject.narrow(
ctx.lookup(“javax.transaction.UserTransaction”),javax.transaction.UserTransaction.class);
© The Middleware Company • http://www.middleware-company.com 23
Mini-Lab: Atomicity and the JTA
Duration: 15 minutes Purpose: To learn how to achieve atomicity through the JTA Instructions:
1) We will be modifying an existing bean: a bank account entity bean
2) Run the bank account client. Notice how it performs a deposit() and a withdraw() and a deposit(), but the deposit() fails. Notice the bank account value has been reduced despite the failed deposit().
3) Wrap the withdraw() and deposit() in a single atomic transaction by looking up and calling the JTA UserTransaction interface. If the operations succeed, commit the transaction, otherwise rollback. Re-run the client; the bank account should no longer be reduced in value when the deposit() fails.
Notes: Modify the skeleton file AccountClient.java located in this tree:
<TMC_HOME>\EJBTransactions\labs\JTA
© The Middleware Company • http://www.middleware-company.com 24
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 25
Programmatic Transactions
© The Middleware Company • http://www.middleware-company.com 26
How to perform programmatic transactions
In programmatic transactions, your bean starts and ends transactions
Step-by-step guide to programmatic transactions:1) Write your bean’s business logic
2) Lookup and use the JTA UserTransaction interface to start and end the transactions
3) Set a deployment descriptor property indicating that you will be performing your own transactions
© The Middleware Company • http://www.middleware-company.com 27
Programmatic TransactionsStep 1: Write your business logic
public class CatalogBean implements javax.ejb.SessionBean {
...
public ResultSet getCatalog() {
try {
// perform JDBC
// return ResultSet
}
catch (Exception e) {
throw new CatalogException(“Error: " + e.toString());
}
}
}
© The Middleware Company • http://www.middleware-company.com 28
Programmatic TransactionsStep 2: Use the JTA to perform transactions
public class CatalogBean implements javax.ejb.SessionBean {...public ResultSet getCatalog() {
javax.transaction.UserTransaction userTran = null;try {
Context ctx = new InitialContext();
userTran = (javax.transaction.UserTransaction)ctx.lookup(“java:comp/UserTransaction”);
userTran.begin();// perform JDBCuserTran.commit();// return ResultSet
}catch (Exception e) {
throw new CatalogException(“Error: " + e.toString());userTran.rollback();
}}
}
© The Middleware Company • http://www.middleware-company.com 29
Programmatic TransactionsStep 3: Set the deployment descriptor
Set the DD so that the app server lets you control transactions:<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>Catalog</ejb-name>
<home>CatalogHome</home>
<remote>Catalog</remote>
<ejb-class>CatalogBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
...
</session>
</enterprise-beans>
</ejb-jar>
© The Middleware Company • http://www.middleware-company.com 30
Programmatic Transactions and Entity Beans
Note: Programmatic transactions work with session beans, not entity beans With entity beans, you must use declarative transactions
Why? The answer is tricky. Let’s see what happens if we try to do our own transactions in
entity beans…
© The Middleware Company • http://www.middleware-company.com 31
Entity bean programmatic transactions example (exceptions not shown)
public class AccountBean implements javax.ejb.EntityBean {public double balance;...
public void deposit(double amt) throws AccountException {Context ctx = new InitialContext();
javax.transaction.UserTransaction userTran =(javax.transaction.UserTransaction)ctx.lookup(“java:comp/UserTransaction”);
userTran.begin();balance += amt;userTran.commit();
}}
Discussion Point: What’s wrong with this code?
© The Middleware Company • http://www.middleware-company.com 32
Let’s try putting the transaction in ejbLoad()or ejbStore()
public class AccountBean implements javax.ejb.EntityBean {public double balance;...
public void ejbLoad() throws Exception {Context ctx = new InitialContext();
javax.transaction.UserTransaction userTran =(javax.transaction.UserTransaction)ctx.lookup(“java:comp/UserTransaction”);
userTran.begin();// JDBC SELECT STATEMENTuserTran.commit();
}}
Discussion Point: What’s wrong with this code?
© The Middleware Company • http://www.middleware-company.com 33
Bean-managed transactions summary
Container loads and stores entity beans on transactional boundaries1) After a transaction begins: ejbLoad()2) During a transaction: get/set methods3) Right before a transaction ends: ejbStore()
A transaction should span all three of these operations If any of them fail, they should all fail
Its impossible for a bean-managed transaction to span all 3 methods! Remember: you don’t call your own methods. The EJB container does! You can’t control when these methods are called, if at all
Therefore, any programmatic transaction in an entity bean is useless Bean-managed transactions are illegal in entity beans with EJB 1.1
Discussion point: The EJB spec allows session beans to use bean-managed transactions, but not entity beans. Why do you think this would be the case?
© The Middleware Company • http://www.middleware-company.com 34
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 35
Declarative Transactions
© The Middleware Company • http://www.middleware-company.com 36
How to perform declarative transactions
In declarative transactions, the EJB Object starts and ends transactions
Transactions occur automatically at the point of interception
Step-by-step guide to declarative transactions:1) Write your bean’s business logic
2) Set a deployment descriptor property indicating that you need transactions from the application server
3) Set a deployment descriptor property indicating the transaction attribute you need (we’ll discuss later)
© The Middleware Company • http://www.middleware-company.com 37
Declarative TransactionsStep 1: Write your business logic
public class AccountBean implements javax.ejb.EntityBean {Bean Implementation
public double balance;
...
// Business methods
public void deposit(double amt) throws AccountException {
balance += amt;
}
}
Of Note: Code is much simpler Transaction will wrap the JDBC calls
© The Middleware Company • http://www.middleware-company.com 38
Declarative TransactionsStep 2: Set the deployment descriptor
Set the DD so that the app server lets you control transactions:<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>Account</ejb-name>
<home>AccountHome</home>
<remote>Account</remote>
<ejb-class>AccountBean</ejb-class>
<transaction-type>Container</transaction-type>
...
</entity>
</enterprise-beans>
</ejb-jar>
© The Middleware Company • http://www.middleware-company.com 39
Declarative TransactionsStep 3: Transaction Attributes
With bean-managed transactions, we controlled how long the transaction umbrella was open for through code.
How do we control this with container-managed transactions?
For example: Do we even need transactions at all? Should our EJB object start his own transaction? If there’s already a transaction going on, should we join it? If there’s already a transaction going on, should we ignore it?
You answer these questions with transaction attributes Transaction attributes are settings in the deployment descriptor They are instructions for how the app server should generate the
transaction code in the EJB object
© The Middleware Company • http://www.middleware-company.com 40
Transaction Attributes
There are many transaction attributes that we’ll see in the next few slides. You set transaction attributes in the <assembly-descriptor> DD entry. For example:<ejb-jar>
...
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>AccountBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
© The Middleware Company • http://www.middleware-company.com 41
The Transaction Attributes
Required Supports Mandatory Not Supported Never Requires New Bean Managed
© The Middleware Company • http://www.middleware-company.com 42
The Supports Transaction Attribute
Some operations are transactional If there’s an existing transaction, you attach to it
Your bean’s transaction runs with the client’s transaction You are not isolated from the client’s operations You see each other’s updates! Transaction concludes when client commits
If no existing transaction, no transaction happens
Discussion point: When would you want to use the supports attribute?
© The Middleware Company • http://www.middleware-company.com 43
The Mandatory Transaction Attribute
All operations are transactional If there’s an existing transaction, you attach to it
Your bean’s transaction runs with the client’s transaction You are not isolated from the client’s operations You see each other’s updates! Transaction concludes when client commits
If no existing transaction, you throw an exception back to the client! This forces clients to start transactions for you
Use this when you want to force yourself to be part of a workflow
© The Middleware Company • http://www.middleware-company.com 44
The NotSupported Transaction Attribute
No operations are transactional Existing transaction is suspended
The client’s transaction is independent of your bean You are not isolated from the client because you don’t
use transactions This mode means no ACID properties! Dangerous
to use! Use this attribute if you are not doing state changes Example: Stateless session bean that multiplies
matrices Do not use this attribute with entity beans!!!
© The Middleware Company • http://www.middleware-company.com 45
The RequiresNew Transaction Attribute
All operations are transactional. Existing transaction is suspended
Your bean’s transaction runs in parallel to the client’s transaction
Each transaction is isolated from one another
New transaction always begins. Guarantees ACID. Transaction begins and ends with your method call
Use this attribute when you want to be isolated from your client (not part of a workflow).
© The Middleware Company • http://www.middleware-company.com 46
The BeanManaged Transaction Attribute
Your bean programmatically controls transactions via the JTA
The existing transaction is suspended Your bean’s transaction runs in parallel to the client’s
transaction Each transaction is isolated from one another
Use this attribute if your bean needs fine-grained control of transactions Example: You need 2 transactions in 1 method
© The Middleware Company • http://www.middleware-company.com 47
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 48
Client-Controlled Transactions
© The Middleware Company • http://www.middleware-company.com 49
Performing transactions from clients
In client transactions, the client starts and ends transactions rather than the EJB object or bean
To control transactions, use the Java Transaction API The application server must publish this API and make it
available via JNDI under the location java:comp/UserTransaction Note: Weblogic does not follow this rule and uses: javax/transaction/UserTransaction
Step-by-step guide to client transactions:1) Lookup the JTA UserTransaction interface via JNDI2) Call UserTransaction.begin()3) Perform your business operations4) Call UserTransaction.commit() or UserTransaction.rollback()
© The Middleware Company • http://www.middleware-company.com 50
Sample client-controlledtransaction code from a servlet
public class BankServlet extends HttpServlet {...public void service(HttpServletRequest request,
HttpServletResponse response) throws Exception {
javax.transaction.UserTransaction userTran = null;try {
javax.naming.Context ctx = new InitialContext(...);userTran = c(javax.transaction.UserTransaction)
ctx.lookup("java:comp/UserTransaction");
userTran.begin();
// perform business operations
userTran.commit();}catch (Exception e) {
userTran.rollback();}
}}
© The Middleware Company • http://www.middleware-company.com 51
Transaction Style Summary
Transaction Style Appropriateness
ProgrammaticUncommonly used
Useful when you need multiple transactions per EJB method call
DeclarativeCommonly used
Useful when you need a single transaction per EJB method call
Client-Controlled
Rarely used
Useful for systems involving non-EJB clients
Client and server should be closely located
© The Middleware Company • http://www.middleware-company.com 52
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 53
How to design transactional conversations
Motivation: A stateful session bean is a transactional resource too. Has in-memory state that needs to rollback in case of
failure. Can participate in transactions like a database by
implementing SessionSynchronization:
public interface javax.ejb.SessionSynchronization {public void afterBegin();public void beforeCompletion();public void afterCompletion(boolean);
}
© The Middleware Company • http://www.middleware-company.com 54
Uses of SessionSynchronization
2 uses of SessionSynchronization:1) Alerts your bean to transaction failure
– If transaction fails, you undo your in-memory state
2) Alerts you to transaction boundaries– Enables you to cache database data for performance
Usage:
afterBegin() Transaction just started Read in database data (create your cache)
Create a backup copy of your state
beforeCompletion Transaction about to end Flush your cache
afterCompletion Transaction has ended If transaction failed, revert to backup copy of your state
© The Middleware Company • http://www.middleware-company.com 55
Code for Designing Transactional Conversations
public class CountBean implements SessionBean, SessionSynchronization {
public int val; public int oldVal;
public void ejbCreate(int val) { this.val=val; this.oldVal=val; }
public void afterBegin() { oldVal = val;} public void beforeCompletion() {} public void afterCompletion(boolean b) { if (b == false) val = oldVal; }
public int count() { return ++val; } public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) {}}
© The Middleware Company • http://www.middleware-company.com 56
SessionSynchronization Lifecycle (Bean View)
© The Middleware Company • http://www.middleware-company.com 57
Mini-Lab: Transactional conversations
Duration: 25 minutes Purpose: To gain experience with constructing session beans that
behave as in-memory databases Instructions:
1) We will be working with an existing bean: the shopping cart. Run the shopping cart client as-is. Notice how we abort a transaction, but our state does not automatically rollback.
2) Modify you’re the cart to be transaction-aware by implementing SessionSynchronization. Perform the necessary checks to undo any state-changing operations in case of transactional failure.
3) Re-run the client. Verify that the shopping cart does indeed undo its state.
Hints: The shopping cart has 2 pieces of state: contents (Vector) and owner (String).
You will need to handle both of these. The contents must be clone()'d, but the String does not (why?).
Notes: Modify the code located in:
c:<TMC_HOME>\EJBTransactions\labs\IMDB
© The Middleware Company • http://www.middleware-company.com 58
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 59
Dooming Transactions If a bean is involved in some larger transaction, it needs a way to force the
transaction to abort Such as when a consistency violation occurs
Your bean can call EJBContext.setRollbackOnly() to force transaction rollback.
public class MyBean implements javax.ejb.EntityBean {
private EntityContext ctx = null;
public void setEntityContext(EntityContext ctx) {this.ctx = ctx;
}...
public void foo() throws Exception {// something bad happened..ctx.setRollbackOnly();
}}
© The Middleware Company • http://www.middleware-company.com 60
The problem with dooming transactions
Doomed transactions decreases scalability If someone else doomed your transaction, why bother
doing compute-intensive operations? Need a way to detect doomed transactions
© The Middleware Company • http://www.middleware-company.com 61
How to detect doomed transactions for scalability
public class MyBean implements javax.ejb.EntityBean {
private EntityContext ctx = null;
public void setEntityContext(EntityContext ctx) {this.ctx = ctx;
}
...
public void performComplexOperation() throws Exception {
if (ctx.getRollbackOnly()) { return; }
else {// perform complex operation
}}
}
© The Middleware Company • http://www.middleware-company.com 62
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 63
Isolation - The "I" in ACID
Problem: Need to share data safely Isolation is the tradeoff between concurrency and
safety EJB 1.0: EJB Isolation Levels put you in control EJB 1.1 and beyond: No EJB isolation levels. Use
JDBC.
Let’s discuss how to properly use isolation We begin by investigating the types of
transactional problems
© The Middleware Company • http://www.middleware-company.com 64
The Dirty Read Problem
TRANSACTION_READ_UNCOMMITTED isolation level allows for this problem to happen
TRANSACTION_READ_COMMITTED isolation level solves this problem
Bean 2
Database
Bean 1
1: X = 0
4: Write X=102: Begin TX
8: Rollback TX6: Read X=103: Begin TX
7: Commit TX
9: X = 0
5: X = 10
© The Middleware Company • http://www.middleware-company.com 65
The Unrepeatable Read Problem
TRANSACTION_READ_COMMITTED isolation level allows for this problem to happen
TRANSACTION_REPEATABLE_READ isolation level solves this problem
Bean 2
Database
Bean 1
1: X = 04: Read X=02: Begin TX
8: Read X=105: Write X=103: Begin TX
6: Commit TX
7: X = 109: Commit TX
© The Middleware Company • http://www.middleware-company.com 66
The Phantom Problem
TRANSACTION_REPEATABLE_READ isolation level allows for this problem to happen
TRANSACTION_SERIALIZABLE isolation level solves this problem
Bean 2
Database
Bean 1
1: 1 row4: SELECT returns 1 row
2: Begin TX
8: SELECT returns 2 rows5: INSERT row3: Begin TX
6: Commit TX
7: 2 rows9: Commit TX
© The Middleware Company • http://www.middleware-company.com 67
Isolation Summary
Isolation Level Dirty Reads? Unrepeatable Reads?
Phantom Reads?
READ UNCOMMITTED
Yes Yes Yes
READ COMMITTED No Yes Yes
REPEATABLE READ
No No Yes
SERIALIZABLE No No No
© The Middleware Company • http://www.middleware-company.com 68
Isolation Summary READ_UNCOMMITTED (fastest)
You can see other transactions’ uncommitted updates No data sharing, non mission-critical apps.
READ_COMMITTED (fast) You can’t see other transactions’ uncommitted updates Rough Reporting tools. Data should be committed. Only need a snapshot.
REPEATABLE_READ (medium) When you read a row, nobody can touch that row until you’re done Mission-critical, high data sharing. You have not performed a query, so
phantoms are OK, so long as the data you're working with isn't modified.
SERIALIZABLE (slow) After you do a query, nobody can insert new rows that satisfies your query until
you’re done Mission-critical, high data sharing. You have performed a query, and you'd like
to know about any new phantom rows.
© The Middleware Company • http://www.middleware-company.com 69
Module Roadmap Transaction Motivation The ACID Properties Transaction Types Controlling Transaction Boundaries in EJB
The Java Transaction API (JTA) Programmatic Transactions Declarative Transactions Client-Controlled Transactions
Designing Transactional Conversations Doomed Transactions Isolation – the “I” in ACID Distributed Transactions
© The Middleware Company • http://www.middleware-company.com 70
Distributed Transactions
Motivation: Have 2 data sources in 1 transaction Example: Database and Message Queue
Normal commit won't work.
Bank TellerSession Bean
Bank Account #1 Entity Bean
Bank Account #2Entity Bean
Money Market
Database
1: withdraw() 3: deposit()
2: balance -= amt 4: balance += amt
5: ejbStore() 6: ejbStore()7: commit()
8: Checking database CRASHES!!
CheckingDatabase
© The Middleware Company • http://www.middleware-company.com 71
The 2-phase commit solution
Idea: split commit into 2 phases Phase 1 – Database operations are complete Phase 2 – Commit or rollback operations
Bank TellerSession Bean
Bank Account #1 Entity Bean
Bank Account #2Entity Bean
Money Market
Database
1: withdraw() 3: deposit()
2: balance -= amt 4: balance += amt
5: ejbStore() 6: ejbStore()
7: prepare()
10: Checking database CRASHES!!
CheckingDatabase
9: commit()
8: prepare()
11: Checking database REBOOTS!!
© The Middleware Company • http://www.middleware-company.com 72
Transaction Propagation
Behind the scenes, transactions use transaction contexts Transaction context identifies the current transaction Typically it is stored in Thread Local Storage (TLS) Idea is this information travels with you regardless of which
beans your thread calls Today, most transactions span a single EJB server
Example: Start transaction in Weblogic, end in Weblogic
Discussion point: Let's review how an EJB invocation is processed. What object is a client calling when he calls a business method? How does the request get routed to a bean?
© The Middleware Company • http://www.middleware-company.com 73
Transaction Propagation
Transactions spanning 2 instances of the same EJB server works today Works since Weblogic stubs understand how to retrieve TX
contexts from TLS in weblogic server
But ultimately we'd like transactions to span multiple EJB servers Example: Start transaction in Weblogic, end in WebSphere
Discussion point: If an EJB #1 running in Weblogic calls an EJB #2 running in WebSphere, did Weblogic or Websphere generate the stub which EJB #1 calls upon?
© The Middleware Company • http://www.middleware-company.com 74
Transaction Propagation Transactions spanning multiple EJB servers does not work
today. Challenges include: How can WebSphere stub know where to find TX context in Weblogic
TLS? How can WebSphere understand Weblogic TX contexts?
There was a great debate about how to fix this Some thought there should be a standard for TX contexts and for their
locations in TLS Other thought there should be a standard protocol in EJB, and the
protocol should contain standard TX information The protocol folks won
Mostly political reasons (vendors had invested much into IIOP and wanted a strategic advantage)
As of EJB 2.0, the IIOP protocol is mandatory So in the future, you should start to see better TX propagation
© The Middleware Company • http://www.middleware-company.com 75
Transaction Tips Summary
Server-side only Keep them short Choose the optimal isolation level Avoid 2-phase commit if possible Use declarative transactions when possible Use session beans as a transactional façade Don't try to get transactions working between 2 EJB
servers quite yet Fortunately, folks are struggling with 1 EJB server as it is! By the time people care about heterogeneous EJB systems,
we should have TX context propagation
© The Middleware Company • http://www.middleware-company.com 76
More information on transactions
Jim Gray’s Transaction Processing book Ullman’s classic book on databases EJB Specification TheServerSide.com
An open EJB/J2EE discussion community Free electronic copy of Ed Roman’s EJB book
There’s more about transactions in that book Get it at http://www.TheServerSide.com
© The Middleware Company • http://www.middleware-company.com 77
Middleware Company
Want to pass this knowledge on? Training Events in Bay Area
May 7-11: J2EE May 14-18: Mastering EJB May 21-25: EJB for Architects
Sign up 30 days before the course and receive a free handheld GPS!
Stop by our exhibition booth or website
http://www.middleware-company.com/
© The Middleware Company • http://www.middleware-company.com 78
Middleware Company
Offering Private Courses for your Company Custom Consulting Available Jump-Start package: Bundle training with
consulting… Your team hits the ground running. New EJB for Architects Course!
© The Middleware Company • http://www.middleware-company.com 79
Middleware Company
Did you like this talk?How would you like to give it yourself?
All employees of The Middleware Company are speakers.
That’s one value of working with us – we offer smart developers the opportunity to become recognized experts
See us at http://www.middleware-company.com Talk to us at [email protected]
© The Middleware Company • http://www.middleware-company.com 80
Questions