Presentation is loading. Please wait.

Presentation is loading. Please wait.

Training and consulting in Java, EJB, J2EE, and XML / Mastering.

Similar presentations


Presentation on theme: "Training and consulting in Java, EJB, J2EE, and XML / Mastering."— Presentation transcript:

1 Training and consulting in Java, EJB, J2EE, and XML / Mastering Transactions Performing atomic, consistent, isolated, and durable operations using Java and EJB

2 © The Middleware Company 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

3 © The Middleware Company 3 Transactions Motivation Client Object Server Object Database Discussion point: What issues might arise in a database in a multi-tier deployment?

4 © The Middleware Company 4 Discussion point: If we get an RMI RemoteException, did the server complete its processing correctly? Transactions Motivation (cont)

5 © The Middleware Company 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: Whats wrong with this code? Transactions Motivation (cont)

6 © The Middleware Company 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.

7 © The Middleware Company 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

8 © The Middleware Company 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?

9 © The Middleware Company 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

10 © The Middleware Company 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.

11 © The Middleware Company 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. SafetyConcurrency

12 © The Middleware Company 12 Durability ACID Property Catastrophic failure is recoverable. If a database crashes, it will reboot and fix itself automatically.

13 © The Middleware Company 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

14 © The Middleware Company 14 Flat transactions Flat transactions are the most common transaction type Supported by all databases Only transaction type supported universally by EJB

15 © The Middleware Company 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.

16 © The Middleware Company 16 Nested transactions

17 © The Middleware Company 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

18 © The Middleware Company 18 Transaction Boundaries Transaction boundaries mark the beginning and end of transactions Analogy is an umbrella When you open the umbrella, youre protected from the rain When you close the umbrella, youre vulnerable again Its up to you to choose the right boundaries Transaction is too long? Concurrency decreases due to collisions with other transactions Transaction is too short? Wont encapsulate your atomic operations 3 Ways to control transactional boundaries: Inside your bean programmatically Inside your bean declaratively From client code

19 © The Middleware Company 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

20 © The Middleware Company 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.

21 © The Middleware Company 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; }

22 © The Middleware Company 22 Looking up the UserTransaction interface The JTA UserTransaction interface is actually an interface to the application servers transaction manager Its 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);

23 © The Middleware Company 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: \EJBTransactions\labs\JTA

24 © The Middleware Company 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

25 © The Middleware Company 25 Programmatic Transactions

26 © The Middleware Company 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 beans 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

27 © The Middleware Company 27 Programmatic Transactions Step 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()); }

28 © The Middleware Company 28 Programmatic Transactions Step 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 JDBC userTran.commit(); // return ResultSet } catch (Exception e) { throw new CatalogException(Error: " + e.toString()); userTran.rollback(); }

29 © The Middleware Company 29 Programmatic Transactions Step 3: Set the deployment descriptor Set the DD so that the app server lets you control transactions: Catalog CatalogHome Catalog CatalogBean Stateless Bean...

30 © The Middleware Company 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. Lets see what happens if we try to do our own transactions in entity beans…

31 © The Middleware Company 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: Whats wrong with this code?

32 © The Middleware Company 32 Lets 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 STATEMENT userTran.commit(); } Discussion Point: Whats wrong with this code?

33 © The Middleware Company 33 Bean-managed transactions summary Container loads and stores entity beans on transactional boundaries 1)After a transaction begins: ejbLoad() 2)During a transaction: get/set methods 3)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 dont call your own methods. The EJB container does! You cant 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?

34 © The Middleware Company 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

35 © The Middleware Company 35 Declarative Transactions

36 © The Middleware Company 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 beans 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 (well discuss later)

37 © The Middleware Company 37 Declarative Transactions Step 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

38 © The Middleware Company 38 Declarative Transactions Step 2: Set the deployment descriptor Set the DD so that the app server lets you control transactions: Account AccountHome Account AccountBean Container...

39 © The Middleware Company 39 Declarative Transactions Step 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 theres already a transaction going on, should we join it? If theres 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

40 © The Middleware Company 40 Transaction Attributes There are many transaction attributes that well see in the next few slides. You set transaction attributes in the DD entry. For example:... AccountBean * Required

41 © The Middleware Company 41 The Transaction Attributes Required Supports Mandatory Not Supported Never Requires New Bean Managed

42 © The Middleware Company 42 The Supports Transaction Attribute Some operations are transactional If theres an existing transaction, you attach to it Your beans transaction runs with the clients transaction You are not isolated from the clients operations You see each others updates! Transaction concludes when client commits If no existing transaction, no transaction happens Discussion point: When would you want to use the supports attribute?

43 © The Middleware Company 43 The Mandatory Transaction Attribute All operations are transactional If theres an existing transaction, you attach to it Your beans transaction runs with the clients transaction You are not isolated from the clients operations You see each others 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

44 © The Middleware Company 44 The NotSupported Transaction Attribute No operations are transactional Existing transaction is suspended The clients transaction is independent of your bean You are not isolated from the client because you dont 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!!!

45 © The Middleware Company 45 The RequiresNew Transaction Attribute All operations are transactional. Existing transaction is suspended Your beans transaction runs in parallel to the clients 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).

46 © The Middleware Company 46 The BeanManaged Transaction Attribute Your bean programmatically controls transactions via the JTA The existing transaction is suspended Your beans transaction runs in parallel to the clients 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

47 © The Middleware Company 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

48 © The Middleware Company 48 Client-Controlled Transactions

49 © The Middleware Company 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 JNDI 2)Call UserTransaction.begin() 3)Perform your business operations 4)Call UserTransaction.commit() or UserTransaction.rollback()

50 © The Middleware Company 50 Sample client-controlled transaction 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(); }

51 © The Middleware Company 51 Transaction Style Summary Transaction StyleAppropriateness Programmatic Uncommonly used Useful when you need multiple transactions per EJB method call Declarative Commonly 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

52 © The Middleware Company 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

53 © The Middleware Company 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); }

54 © The Middleware Company 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 startedRead in database data (create your cache) Create a backup copy of your state beforeCompletion Transaction about to endFlush your cache afterCompletion Transaction has endedIf transaction failed, revert to backup copy of your state

55 © The Middleware Company 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) {} }

56 © The Middleware Company 56 SessionSynchronization Lifecycle (Bean View)

57 © The Middleware Company 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 youre 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: \EJBTransactions\labs\IMDB

58 © The Middleware Company 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

59 © The Middleware Company 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(); }

60 © The Middleware Company 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

61 © The Middleware Company 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 }

62 © The Middleware Company 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

63 © The Middleware Company 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. Lets discuss how to properly use isolation We begin by investigating the types of transactional problems

64 © The Middleware Company 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=10 2: Begin TX 8: Rollback TX 6: Read X=10 3: Begin TX 7: Commit TX 9: X = 0 5: X = 10

65 © The Middleware Company 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 = 0 4: Read X=0 2: Begin TX 8: Read X=10 5: Write X=10 3: Begin TX 6: Commit TX 7: X = 10 9: Commit TX

66 © The Middleware Company 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 row 4: SELECT returns 1 row 2: Begin TX 8: SELECT returns 2 rows 5: INSERT row 3: Begin TX 6: Commit TX 7: 2 rows 9: Commit TX

67 © The Middleware Company 67 Isolation Summary Isolation LevelDirty Reads?Unrepeatable Reads? Phantom Reads? READ UNCOMMITTED Yes READ COMMITTEDNoYes REPEATABLE READ No Yes SERIALIZABLENo

68 © The Middleware Company 68 Isolation Summary READ_UNCOMMITTED (fastest) You can see other transactions uncommitted updates No data sharing, non mission-critical apps. READ_COMMITTED (fast) You cant 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 youre 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 youre done Mission-critical, high data sharing. You have performed a query, and you'd like to know about any new phantom rows.

69 © The Middleware Company 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

70 © The Middleware Company 70 Distributed Transactions Motivation: Have 2 data sources in 1 transaction Example: Database and Message Queue Normal commit won't work. Bank Teller Session Bean Bank Account #1 Entity Bean Bank Account #2 Entity Bean Money Market Database 1: withdraw() 3: deposit() 2: balance -= amt4: balance += amt 5: ejbStore()6: ejbStore()7: commit() 8: Checking database CRASHES!! Checking Database

71 © The Middleware Company 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 Teller Session Bean Bank Account #1 Entity Bean Bank Account #2 Entity Bean Money Market Database 1: withdraw() 3: deposit() 2: balance -= amt4: balance += amt 5: ejbStore()6: ejbStore() 7: prepare() 10: Checking database CRASHES!! Checking Database 9: commit() 8: prepare() 11: Checking database REBOOTS!!

72 © The Middleware Company 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?

73 © The Middleware Company 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?

74 © The Middleware Company 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

75 © The Middleware Company 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

76 © The Middleware Company 76 More information on transactions Jim Grays Transaction Processing book Ullmans classic book on databases EJB Specification TheServerSide.com An open EJB/J2EE discussion community Free electronic copy of Ed Romans EJB book Theres more about transactions in that book Get it at

77 © The Middleware Company 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

78 © The Middleware Company 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!

79 © The Middleware Company 79 Middleware Company Did you like this talk? How would you like to give it yourself? All employees of The Middleware Company are speakers. Thats one value of working with us – we offer smart developers the opportunity to become recognized experts See us at Talk to us at

80 © The Middleware Company 80 Questions


Download ppt "Training and consulting in Java, EJB, J2EE, and XML / Mastering."

Similar presentations


Ads by Google