53
Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

Embed Size (px)

Citation preview

Page 1: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

EnterpriseJava

Transactions

Source:

“Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

Page 2: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 2

EnterpriseJava

Transaction Definition

• Unit of work that accesses one or more shared resources (usually databases) – set of one or more activities related to each other– must be completed together or not at all– cohesion of unit is normally mission critical– examples

• ATM – withdraw from one source, deposit to another

• Order System– locate item, charge account, schedule shipment

• Medical System– identify medical state, dispense prescription

Page 3: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 3

EnterpriseJava

Transaction Properties

• Atomic– Transaction must execute completely or not at all

• Consistent– Data in database is always in a consistent state (makes

sense)

– constraints (primary keys, referential integrity, etc.)

• Isolated– Transaction executes without interference

• Durable– changes are not lost if the system crashes

Page 4: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 4

EnterpriseJava

EJB Transaction Support

• Declarative– transaction management controlled through deployment

descriptor

• Programmatic– direct programming calls to Java Transaction Service

(JTS) API

– transaction management code mixed with business code

– change in transactional behavior requires change in business code

Page 5: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 5

EnterpriseJava

Transaction Scope

• (one or more tasks that operate as a unit of work; succeed or be rolled back together)

• Tasks – EJB methods

• Unit of Work– Each bean visited by the methods during a thread of

execution depending on bean transaction attributes

– ends when thread of execution • completes normally

• an exception is thrown

• transaction is rolled back

Page 6: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 6

EnterpriseJava

Transaction Attributes

• Supports Transactions – Supports@

– Required*

– RequiresNew*

– Mandatory** Recommended for CMP 2.0 Entity Beans; support required

• Transactions not Supported– NotSupported@

– Never@@ support optional for CMP 2.0 Entity Beans

Page 7: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 7

EnterpriseJavaSetting the

Declarative Transaction Attribute<ejb-jar>

...

<assembly-descriptor>

<container-transaction>

<method>

<ejb-name>Account</ejb-name>

<method-name>*</method-name>

</method>

<trans-attribute>Supports</trans-attribute>

</container-transaction>

</assembly-descriptor>

</ejb-jar>

Page 8: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 8

EnterpriseJava

Container and Beans

Pool

Home

EJBObject

HomeInterface

HomeStub

RemoteInterface

RemoteObjectStub

AccountBean

Client

Container

create

transfer

Page 9: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 9

EnterpriseJava

Not Supported

Invoked EJBClient

Thread of Execution Client’s Transaction Context No Transaction Context

• Transaction is suspended during the method of the Invoked EJB; resumes when method complete

• Transaction scope is not propagated to Invoked EJB or anything it invokes

Page 10: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 10

EnterpriseJava

SupportsInvoked EJBClient

• Joins the transaction context if invoked as part of a transaction (A)

• Does not require a transaction; can be invoked outside of a transaction context (B)

Thread of Execution Client’s Transaction Context No Transaction Context

(A)

(B)

Page 11: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 11

EnterpriseJava

RequiredInvoked EJBClient

• Joins the transaction context if invoked as part of a transaction (A)

• Initiates its own transaction context of invoked outside of a transaction (B)

Thread of Execution Client’s Transaction Context No Transaction Context

(A)

(B)

EJB’s Transaction Context

Page 12: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 12

EnterpriseJava

RequiresNewInvoked EJBClient

• Initiates its own transaction context whether called within am existing transaction context (A) or outside of a transaction context (B)

• Initiated transaction completes prior to returning to caller

Thread of Execution Client’s Transaction Context No Transaction Context

(A)

(B)

EJB’s Transaction Context

Page 13: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 13

EnterpriseJava

MandatoryInvoked EJBClient

• Joins the transaction context if invoked as part of a transaction (A)• Throws a Transaction Exception if not called within a transaction

context (B) (TransactionRequiredException for Remote Clients; TransactionRequiredLocalException for Local Clients)

Thread of Execution Client’s Transaction Context No Transaction Context

(A)

(B)Transaction Exception

Page 14: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 14

EnterpriseJava

NeverInvoked EJBClient

• Throws a Transaction Exception if called within a transaction context (A) (RemoteException to Remote Clients; EJBException to Local Clients)

• Must be invoked outside of a transaction context (B)

Thread of Execution Client’s Transaction Context No Transaction Context

(A)

(B)

Transaction Exception

Page 15: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 15

EnterpriseJava

Isolation and Database Locking

• What happens when two or more transactions attempt to access the same data– Dirty Reads

• first transaction reads uncommitted changes from a second transaction that may eventually be rolled back

– Repeatable Reads• data guaranteed to be the same if read multiple times during

the same transaction; implemented with locks or snapshots

– Phantom Reads• first transaction sees new rows added by second transaction

after beginning of the first transaction

Page 16: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 16

EnterpriseJava

Database Locks

• How do you prevent overlapping transactions from viewing the other’s data– Read Lock

• data is prevented from changing while transaction in progress

– Write Lock• prevents other transactions from modifying the data

• permits dirty reads by other transactions

– Exclusive Write Lock• prevents other transactions from reading and modifying data

• prevents dirty reads

– Snapshots - frozen view of data

Page 17: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 17

EnterpriseJava

Transaction Isolation Levels

• Read Uncommitted• can read data being modified by another transaction• allows dirty, non-repeatable, and phantom reads

• Read Committed• cannot read data being modified by another transaction• allows non-repeatable and phantom reads; prevents dirty reads

• Repeatable Read• cannot change data being read by another transaction• allows phantom reads; prevents dirty and non-repeatable reads

• Serializable• transactions can neither read or write same data

Page 18: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 18

EnterpriseJava

Specifying Isolation Level

<weblogic-ejb-jar>

<transaction-isolation>

<!-- TRANSACTION_SERIALIZABLE

TRANSACTION_READ_COMMITTED

TRANSACTION_READ_UNCOMMITTED

TRANSACTION_REPEATABLE_READ

-->

<isolation-level>TRANSACTION_READ_COMMITTED</isolation-level>

<method>

<ejb-name>Account</ejb-name>

<method-name>*</method-name>

<method>

</transaction-isolation>

Page 19: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 19

EnterpriseJava

Message Driven Bean Transactions

• Valid Values– Not Supported

– Required

• Client transaction context not propagated to MDB– Supports, RequiresNew, Mandatory, and Never are

relative to client

Page 20: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 20

EnterpriseJava

Exceptions within Transactions

• System Exceptions (ex. NullPointerException, EJBException)– container automatically rolls back transaction

– bean instance is discarded

• ApplicationException (ex. AccountOverdrawException)– container does not automatically rollback transaction

– exception delivered to client

– client optionally signals rollback• EJBContext.setRollbackOnly()

Page 21: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 21

EnterpriseJava

CMR and Transactions

• Collections obtained through CMR must be accessed within the same transactionpublic void processAccounts(CustomerLocal customer) {

Collection accounts = customer.getAccounts();

for (Iterator i=accounts.iterator(); i.hasNext(); ) {

}

}

– processAccounts must have a transaction context active or will receive a java.lang.IllegalStateException when accessing accounts

Page 22: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 22

EnterpriseJava

Transaction/Bank Example

• Account – Entity Bean– Deployments (NotSupported, Supports, RequiresNew)– reports Application Exception (on overdraw)

• Teller– Stateless Session Bean– Deployments (Required)– calls EJBContext.setRollbackOnly() on exception

• TxClient/TxClientMain– instantiates Accounts with varying transaction support– uses Teller to perform actions on Accounts

Page 23: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 23

EnterpriseJava

AccountEJB

public abstract class AccountEJB implements EntityBean {

public void reset() { setBalance(0.0F); }

public void deposit(float amount) throws AccountException {

setBalance(getBalance() + amount);

}

public void withdraw(float amount) throws AccountException {

float balance = getBalance();

if ((balance - amount) >= 0) { setBalance(balance - amount); }

else {

setBalance(balance - 1.0F); //subtract fee

throw new AccountException("overdraw");

}

}

...

Page 24: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 24

EnterpriseJava

TellerEJBpublic class TellerEJB implements SessionBean {

public void transfer(

AccountRemote fromAccount, AccountRemote toAccount, float amount)

throws AccountException {

try {

toAccount.deposit(amount);

fromAccount.withdraw(amount);

}

catch (AccountException ex) {ctx_.setRollbackOnly(); throw ex; }

}

public void reset(AccountRemote account) //similar to transfer

}

Page 25: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 25

EnterpriseJava

TxClient Initialization

fromAccounts_ = new Hashtable(LAST_TYPE);

toAccounts_ = new Hashtable(LAST_TYPE);

for(int i=FIRST_TYPE; i<=LAST_TYPE; i++) {

String id = uidGenerator_.createUID().toString();

AccountRemote account = createAccount(TX_TYPE[i], id);

toAccounts_.put(TX_TYPE[i], account);

id = uidGenerator_.createUID().toString();

account = createAccount(TX_TYPE[i], id);

fromAccounts_.put(TX_TYPE[i], account);

}

Page 26: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 26

EnterpriseJava

TxClient Transfer

void transfer(int fromType, int toType) throws Exception {

AccountRemote from = ...

AccountRemote to = …

teller_.reset(from); teller_.reset(to);

float amount = 5.00F;

try {

teller_.transfer(from, to, amount);

}

catch (AccountException ex) { System.out.print("transfer failed: " + ex); }

finally {

System.out.println(":from(" +from.getId()+ ")=" + from.getBalance() +

", to=(" +to.getId()+ ")=" + to.getBalance());

}

Page 27: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 27

EnterpriseJava

TxClient Execution

private static void execute(final Context jndi) throws Exception {

TxClient client = new TxClient(jndi);

for(int i=FIRST_TYPE; i<=LAST_TYPE; i++) {

for(int j=FIRST_TYPE; j<=LAST_TYPE; j++) {

System.out.println(TX_TYPE[i] + "->" + TX_TYPE[j]);

client.transfer(i,j);

}

}

}

Page 28: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 28

EnterpriseJava

Running the Example

• Deploy the EJB/EAR– $ coredev txBankApp init

• Run the Client– $ coredev txBankApp

Page 29: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 29

EnterpriseJava

TxClient Output

NotSupported->NotSupported

transfer failed: overdraw:from(19197 )=-1.0, to=(19196 )=5.0

NotSupported->Supports

transfer failed: overdraw:from(19197 )=-1.0, to=(19198 )=0.0

NotSupported->RequiresNew

transfer failed: overdraw:from(19197 )=-1.0, to=(19200 )=5.0

Supports->NotSupported

transfer failed: overdraw:from(19199 )=0.0, to=(19196 )=5.0

Supports->Supports

transfer failed: overdraw:from(19199 )=0.0, to=(19198 )=0.0

Supports->RequiresNew

transfer failed: overdraw:from(19199 )=0.0, to=(19200 )=5.0

Page 30: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 30

EnterpriseJava

TxClient Output

RequiresNew->NotSupported

transfer failed: overdraw:from(19201 )=-1.0, to=(19196 )=5.0

RequiresNew->Supports

transfer failed: overdraw:from(19201 )=-1.0, to=(19198 )=0.0

RequiresNew->RequiresNew

transfer failed: overdraw:from(19201 )=-1.0, to=(19200 )=5.0

<Additional Output>

DEFAULT->DEFAULT

transfer failed: overdraw:from(19203 )=0.0, to=(19202 )=0.0

Page 31: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 31

EnterpriseJavaManaging the transfer()

Transaction Context

to:AccountEJB

from:AccountEJB

TellerEJB

Transaction Manager

TxClient

1: transfer()

2: registerTellerEJB

Supports

Supports

Required

Transaction Context•TellerEJB•to:AccountEJB•from:AccountEJB

3: create tx context;add TellerEJB

4: deposit

5: register to:AccountEJB

6: add to:AccountEJB

7: withdraw

8: register from:AccountEJB

9: add from:AccountEJB

10: verify all will work

11: commitor rollback all updates

Page 32: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 32

EnterpriseJavaDistributed Tx Architecture

Two Phase Commit (2-PC/TPC)

TransactionCoordinator

TXManager

TXManager

ResourceManager

ResourceManager

1. Prepare to Commit

2. Return

3. Log Result

4. commit

5. return

Page 33: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 33

EnterpriseJava

Resource Managers

• Examples– JDBC Drivers

– JMS Provider

Page 34: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 34

EnterpriseJavaAdding Another Resource Manager

(JMS) to Teller public void transfer(

AccountRemote fromAccount, AccountRemote toAccount, float amount)

throws AccountException {

try {

msg_.setString("type", "transfer");

//...

publisher_.publish(msg_);

toAccount.deposit(amount);

fromAccount.withdraw(amount);

}

catch (AccountException ex) { ctx_.setRollbackOnly(); throw ex; }

//...

} //reset() is similar to transfer

Page 35: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 35

EnterpriseJava

Checking commited Results in TxClient

try {

teller_.reset(from);

teller_.reset(to);

}

finally {

if (subscriber_.receive(1000 * 1) == null) {

System.out.println("didn't get first reset message");

}

if (subscriber_.receive(1000 * 1) == null) {

System.out.println("didn't get second reset message");

}

}

Page 36: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 36

EnterpriseJava

Checking rollback Results in TxClient

try { teller_.transfer(from, to, amount); }

catch (AccountException ex) {

System.out.print("transfer failed: " + ex.getMessage());

}

finally {

System.out.print(":from(" +from.getId()+ ")=" + from.getBalance() +

", to=(" +to.getId()+ ")=" + to.getBalance());

if (subscriber_.receive(1000 * 1) == null) {

System.out.println(":no message");

}

}

}

Page 37: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 37

EnterpriseJavaTxClient Output with

Two Resource Managers//note that resets received expected messages

NotSupported->NotSupported

transfer failed: overdraw:from(19205 )=-1.0, to=(19204 )=5.0:no message

NotSupported->Supports

transfer failed: overdraw:from(19205 )=-1.0, to=(19206 )=0.0:no message

NotSupported->RequiresNew

transfer failed: overdraw:from(19205 )=-1.0, to=(19208 )=5.0:no message

Supports->NotSupported

transfer failed: overdraw:from(19207 )=0.0, to=(19204 )=5.0:no message

Supports->Supports

transfer failed: overdraw:from(19207 )=0.0, to=(19206 )=0.0:no message

Supports->RequiresNew

transfer failed: overdraw:from(19207 )=0.0, to=(19208 )=5.0:no message

Page 38: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 38

EnterpriseJavaTxClient Output with

Two Resource ManagersRequiresNew->NotSupported

transfer failed: overdraw:from(19209 )=-1.0, to=(19204 )=5.0:no message

RequiresNew->Supports

transfer failed: overdraw:from(19209 )=-1.0, to=(19206 )=0.0:no message

RequiresNew->RequiresNew

transfer failed: overdraw:from(19209 )=-1.0, to=(19208 )=5.0:no message

//extra output

DEFAULT->DEFAULT

transfer failed: overdraw:from(19211 )=0.0, to=(19210 )=0.0:no message

Page 39: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 39

EnterpriseJavaEnable 2PC Transactions

for Connection Pool

Page 40: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 40

EnterpriseJava

Enable JTS Transactions in Entity Bean

<weblogic-rdbms-jar>

<weblogic-rdbms-bean>

<ejb-name>Account</ejb-name>

<data-source-name>corej2ee.jdbc.corej2eeTxDS</data-source-name>

<table-map>

<table-name>txbank_Account</table-name>

Page 41: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 41

EnterpriseJava

Enable JTS Transactions for JMS

Page 42: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 42

EnterpriseJava

Bean Types and Transactions

• Entity– In EJB 1.1 must be container managed

– may force a rollback with setRollbackOnly()

• Stateless Session– transactions simple. Abort by throwing EJBException

• Stateful Session– What about the conversational state ?

– Have to respond to transaction aborts to keep conversational state consistent

Page 43: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 43

EnterpriseJavaStateful Session Bean

and Transactions (Cont)• Can implement Session Synchronization interface

– afterBegin(), beforeCompletion(), afterCompletion(boolean)

• If afterCompletion is false, you can roll back the conversational state

• SessionSynchronization can not be implemented with bean-managed tx

Page 44: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 44

EnterpriseJava

SessionSynchronization Example

public class SessionSynchronizedTellerEJB

implements SessionBean, javax.ejb.SessionSynchronization {

public void reset(AccountRemote account) throws AccountException { ...

public void transfer(

AccountRemote fromAccount, AccountRemote toAccount, float amount)

throws AccountException { ...

public void afterBegin() {}

public void beforeCompletion() {}

public void afterCompletion(boolean committed) { }

}

Page 45: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 45

EnterpriseJava

Programmatic Transactions

• Bean programmer is responsible for issuing begin(), commit(), and abort() calls in code

• Discouraged - Why not let the container do it ?• Use Java Transaction API (JTA)

– Simple layer over Java Transaction Service (JTS) which is an implementation of the CORBA Object Transaction Service (OTS)

Page 46: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 46

EnterpriseJava

User Transaction

• Required EJB Transaction interface• Provides access to transaction service

– can start and commit

– can mark that transaction must be rolled back

• Client and server components can use• Container/Server does not have to expose JTS API

to the bean

Page 47: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 47

EnterpriseJava

User Transaction

U s e rTra n s a ctio n

b e g in () : vo id

co m m it() : vo id

g e tS ta tu s () : in t

ro ll ba ck() : vo id

s e tRo llb a ckOn ly() : vo id

s e tTra n s a ctio n Tim e o u t(in t) : vo id

<<In te rfa ce >>EJBC o n te xt

ge tC a ll erId e n tity() : Id e n tity

g e tC a l le rP r in cip a l () : P ri n ci p a l

g e tEJ BHo m e () : EJBH o m e

g e tEnvir o n m e n t( ) : P ro p e rt ie s

g e tR o llb a ckOn ly() : b o o le a n

g e tU s e rTra n s a ct io n () : U s e r Tra n s a ct io n

is C a lle rIn R o le( a rg 0 : S t ri n g) : b o o le a n

is C a lle rIn R o le (a rg 0 : Id e n tity) : b o o le a n

s e tR o llb a ckOn ly() : vo id

<<In te rfa ce >>

Page 48: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 48

EnterpriseJava

Code Example

public void transfer(AccountRemote from, AccountRemote to, float amount )

throws AccountException

{

UserTransaction tx = null;

try {

tx = ctx_.getUserTransaction();

tx.begin();

// perform JDBC operations and transfer the money

tx.commit();

} catch (Exception ex) {

tx.setRollbackOnly();

throw new AccountException();

}

}

Page 49: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 49

EnterpriseJava

Programmatic Transactions in EJB

• Allowed in Session Beans<session>

...

<transaction-type>Bean</transaction-type>

– Stateless Session Beans must begin/end in same method

– Stateful Session Beans may begin/end in separate methods (although not advised)

• EJB 1.1 disallows this for Entity Beans• Bean controls transactions programmatically

Page 50: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 50

EnterpriseJava

Transactional Clients

• End user can also control transactions

UserTransaction ut = (UserTransaction) jndiContext.lookup(“javax.transaction.UserTransaction”);

ut.begin();

// perform multiple operations on beans

account1.deposit( 34 );

account2.withdraw( 34 );

ut.commit();

Page 51: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 51

EnterpriseJava

Client Issues

• Lots of network traffic required when client manages transactions

• More complicated• Should have asked a session bean to perform the

set of operations over on the server• Transactions should be short

Page 52: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 52

EnterpriseJava

Performance Implications

• Avoid distributed transactions across multiple resource managers and/or multiple transaction managers– Consider JMS synchronization

• Avoid client control of transaction boundaries– Try to encapsulate transactional business operations in

session beans

Page 53: Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel

v041130 Transactions 53

EnterpriseJava

EJB Transaction Summary

• Supports EJB goal of removing middleware programming burden from bean programmer

• Declare transactional requirements in deployment descriptor

• Transactions have performance implications– limit client control, distributed transactions

– can control frequency of ejbLoad and ejbStore