Beruflich Dokumente
Kultur Dokumente
1
Agenda
• Transaction definitions
• Overview of java transaction API
• Declarative transaction management:
– EJB™ deployment descriptor transaction
attributes
• ATM transaction example to demonstrate
transaction attributes and EJB™ JTS
• Explicit transaction management:
– javax.Transaction.UserTransaction API
• Transaction aware Stateful session
beans
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
2
Transaction Example
Transfer
Teller Account 1
1. Withdraw
Account 2
2. Deposit
3
A Transaction Is a Unit of Work That Has the Following
(ACID) Characteristics:
4
ACID
• Concurrency Control:
– Locking guarantees consistency and
Isolation given Atomicity
• Logging and Recovery:
– Guarantees Atomicity and Durability
5
Transaction Processing
Characteristics
Typically updates data in a database
Reliability of transaction results are
critical. (All changes or none)
Requirements
Ability to abort or commit all changes
Transactions
Transactions are a proven technique for simplifying application programming.
Transactions free the
application programmer from dealing with the complex issues of failure
recovery and multi-user programming.
If the application programmer uses transactions, the programmer divides the
application’s
work into units called transactions. The transactional system ensures that a unit
of work either fully
completes, or the work is fully rolled back. Furthermore, transactions make it
possible for the programmer
to design the application as if it ran in an environment that executes units of
work serially.
6
Transactions
Database
7
Global Transactions
Data Base
Data Base
8
2 Phase Commit
Transaction
Manager
prepare
prepare
ready
ready
Resource Resource
Manager commit/ commit/ Manager
or rollback or rollback
Two-Phase Commit
The two phase commit protocol allows any server that is taking part in a transaction to abort its part of the transaction
and, as a result, force the transaction as a whole to be aborted. To achieve this the two phase commit protocol breaks
the commitment process into two phases. In the first phase, the transaction manager initiates a vote after it receives
a commit request from the client. It sends a prepare message to each server that is participating in the transaction and
waits for a response from each server that indicates whether that server can commit or whether it must rollback. Upon
receipt of the prepare message each server checks to see if it is able to commit its part of the transaction and then votes
for either a commit or an abort accordingly. Once a server has voted to commit a transaction it is not allowed to abort
it. This has serious implications for the server because it must ensure that it can commit even in the event of a server
failure and restart. Once a server has ensured that it can commit and has cast its vote it is in the preparedstate.
When the transaction manager has collected all of votes from the participating servers it initiates the second phase of
the protocol. If all of the servers vote to commit the transaction then the transaction manager sends a message to all of
the servers telling them to commit their part of the transaction. If one or more servers vote to abort the transaction
then the transaction manager sends a message to the servers telling them to abort their part of the transaction.
9
Transaction Demarcation
10
Transaction Context
11
OMG Object Transaction Service
Transaction
Transaction Service context
Distributed transaction processing ensures that application processing can span multiple databases on multiple systems
coordinated by multiple transaction managers. Transaction processing in a distributed system environment requires the
cooperation of three different components: the Transaction Manager (TM) who serves as the transaction coordinator
by providing transaction services to the applications, the Resource Manager (RM) who participates in the transaction
by performing work on behalf of the applications, and the application program whose business logic requires
transaction services. Each of these roles contributes to the Distributed Transaction Processing (DTP) system by
implementing different sets of transaction API and functionality.
Resources are registered with the Transaction Service. The Transaction Service drives the commit protocol by
issuing requests to the resources registered for a transaction.
12
Java Transaction Service
resource
EJB
Transactional
operation
UserTransaction TransactionManager XAResource
interface Interface interface
Transaction
Transaction Service context
• A transaction manager provides the services and management functions required to support
transaction demarcation, transactional resource management, synchronization, and transaction context
propagation.
• An application server (or TP monitor) provides the infrastructure required to support the application
run-time environment which includes transaction state management. An example of such an application
server is an EJB™ server.
• A resource manager (through a resource adapter ) provides the application access to resources. The
resource manager implements a transaction resource interface that is used by the transaction manager to
communicate transaction association, transaction completion, and recovery work. An example of such a
resource manager is a relational database server.
13
Java Transaction Service
JTS is a Java implementation of the Object Management Group's (OMG) Object Transaction Service (OTS)
specification. JTS provides methods for starting, committing, and rolling back transactions, as well as the means to
retrieve the current transaction context.
Enterprise JavaBeans applications communicate with a transaction service using the Java Transaction API (JTA).
JTA provides a programming interface to start transactions, join existing transactions, commit transactions, and roll-
back transactions.
Distributed transaction services in Enterprise Java middleware involve five players: the transaction manager, the
application server, the resource manager, the application program, and the communication resource manager. Each
player contributes to the distributed transaction processing system by implementing different sets of transaction APIs
and functionalities.
• A transaction manager provides the services and management functions required to support transaction
demarcation, transactional resource management, synchronization, and transaction context propagation.
• An application server (or TP monitor) provides the infrastructure required to support the application run-time
environment which includes transaction state management. An example of such an application server is an EJB™
server.
• A resource manager (through a resource adapter ) provides the application access to resources. The resource
manager implements a transaction resource interface that is used by the transaction manager to communicate
transaction association, transaction completion, and recovery work. An example of such a resource manager is a
relational database server.
• A component-based transactional application that operates in a modern application server environment relies on the
EJB™ application server to provide transaction management support through declarative transaction attribute
settings. In addition, other standalone Java client programs may wish to control their transaction boundaries using a
high-level interface provided by the application server or the transaction manager.
• A communication resource manager (CRM) supports transaction context propagation and access to the transaction
service for incoming and outgoing requests. The JTS document does not specify requirements pertaining to
communication. The CRM is present to support transaction propagation as defined in the CORBA OTS and GIOP
specifications.
only high-level interfaces need to be defined to allow transaction demarcation, resource enlistment, synchronization,
and recovery process to be driven by the users of the transaction services.
14
Transaction Manager
transaction manager
• provides the services and management
functions required to support transaction
demarcation, transactional resource
management, synchronization, and
transaction context propagation.
• Initiate and coordinate two-phase commit
and recovery protocol with the resource
managers.
15
Transaction Management
A EJB EJB
Session
S Container Global
Session
EJB EJB
Local
Container-managed Bean-managed
Servlet
JTA Transactions
JDBC Transactions
Transaction
Manager
Data Base
Resource Resource
Manager Manager
Data Base
A transaction manager provides the services and management functions required to support
transaction demarcation, transactional resource management, synchronization, and transaction context
propagation.
• An application server (or TP monitor) provides the infrastructure required to support the application
run-time environment which includes transaction state management. An example of such an application
server is an EJB™ server.
• A resource manager (through a resource adapter ) provides the application access to resources. The
resource manager implements a transaction resource interface that is used by the transaction manager to
communicate transaction association, transaction completion, and recovery work. An example of such a
resource manager is a relational database server.
16
Java Transaction API
•UserTransaction interface
–Enables application to demarcate transaction boundaries
•begin, commit, getStatus,
getStatus, rollback,
rollback, setRollbackOnly,
setRollbackOnly,
setTransactionTimeout
–Exposed by application server
–Called by applications
–Implemented by transaction manager
•A transaction manager provides the services and management functions required to support
transaction demarcation, transactional resource management, synchronization, and transaction context
propagation.
•UserTransaction interface: used by client program or session bean (bean managed transaction
attribute)
•standalone Java client programs may wish to control their transaction boundaries using a high-level
interface provided by the application server or the transaction manager.
17
Java Transaction API
•TransactionManager interface
–Allows application server to demarcate transaction
boundaries on behalf of managed applications.
–Called by the application server
–Implemented by the transaction manager
18
XA Interface
Java Application
Database 1
Database 2
Transaction
Resource Manager
Managers (TM)
Database 3 (RMs)
XAResource
19
JTA
•XAResource interface
–Enables transaction manager to perform three
types of operations:
•Associate and disassociate transaction work with
resources
•Coordinate transaction completion using the two-
two-
phase commit protocol
•Perform transaction recovery after crash
–Exposed by the resource adapter (driver)
–Implemented by the resource adapter and
underlying resource manager
–Called by the transaction manager
20
EJB™ Transactions
21
Declarative Transaction Management
22
TX_NOT_SUPPORTED
Client/caller Server/called
Transaction bean
context1
TX_NOT_SUPPORTED
•does not execute in a transaction
•existing transaction is suspended
The NotSupported transaction attribute can be used when the resource
manager responsible for the transaction is not supported by the J2EE
product. For example, if a bean method is invoking an operation on an
enterprise resource planning system that is not integrated with the J2EE server,
the server has no control over that system’s transactions. In this case, it is best
to set the transaction attribute of the bean to be NotSupported to clearly
indicate that the enterprise resource planning system is not accessed within a
JTA transaction.
23
TX_SUPPORTS
Client/caller Server/called
Transaction bean Transaction
context1 context1
Client/caller Server/called
bean
No Transaction context
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
TX_SUPPORTS
•does not start a new transaction
•Can execute in existing transaction
Typically, the Supports attribute is used instead of the Required attribute as a
performance optimization. However, this optimization should be used with
caution. Mission Critical operations should not use this attribute.
We do not recommend using the transaction attribute Supports. An
enterprise bean with this attribute would have transactional behavior that
differed depending on whether the caller is associated with a transaction
context, leading to possibly a violation of the ACID rules for transactions.
24
TX_REQUIRED
Client/caller Server/called
Transaction bean Transaction
context1 context1
client or container Transaction context
tx.begin, call bean
tx.commit or tx.abort
propagated
Client/caller Server/called
bean Transaction
context1
TX_REQUIRED
•can use existing transaction
•If not already in transaction will start new one, commit when method
completes
Required
If the client is running within a transaction and it invokes the enterprise bean's
method, the method executes within the client's transaction. If the client is not
associated with a transaction, the container starts a new transaction before
running the method. The Required attribute will work for most transactions.
Therefore, you may want to use it as a default, at least in the early phases of
development. Because transaction attributes are declarative, you can easily
change them at a later time.
This transaction attribute should be used whenever the bean is accessing any
transactional resource manager. For example, a bean accessing a database
through JDBC should use the transaction attribute Required. You should use
this if you want the operation to always run in a transaction.
The default choice for a transaction attribute should be Required. Using
this attribute ensures that the methods of an enterprise bean are invoked under
a JTA transaction. In addition, enterprise beans with the Required transaction
attribute can be easily composed to perform work under the scope of a single
JTA transaction.
25
TX_REQUIRES_NEW
Client/caller Server/called
Transaction bean Transaction
context1 context2
client or container New Transaction context created
utx.begin, call bean Container performs:
utx.commit or utx.abort utx.suspend
tx.begin, Call bean, tx.commit/tx.rollback
utx.resume
Client/caller Server/called
bean Transaction
context1
New Transaction context created
Container performs:
tx.begin
Call bean , tx.commit or tx.rollback
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
TX_REQUIRES_NEW
•always starts new transaction, commit when complete
•Suspends existing transaction
The container starts a new transaction for this enterprise bean method and tries
to commit the transaction before sending method results to the client.
The RequiresNew transaction attribute is useful when the bean method needs
to commit its results unconditionally, whether or not a transaction is
already in progress. An example of this requirement is a bean method that
performs logging. This bean method should be invoked with RequiresNew
transaction attribute so that the logging records are created even if the calling
client’s transaction is rolled back.
26
TX_BEAN_MANAGED
Client/caller Server/called
Transaction bean Transaction
context1 context2
Client/caller Server/called
bean Transaction
context1
TX_BEAN_MANAGED
•bean uses JTA to control transaction
•Always creates new transaction context
In most cases it is better to use declarative transactions as opposed to hard
coding bean managed transactions.
If one bean method is tx_bean_managed then they all must be.
27
TX_MANDATORY
Client/caller Server/called
Transaction bean Transaction
context1 context1
client or container
tx.begin, call bean,
Transaction context
tx.commit or tx.abort propagated
Client/caller Server/called
bean
Throws Exception
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
TX_MANDATORY
•must be called within a transaction or will throw exception
Use TX_Mandatory when the component is designed only to run within a
larger system and you want to mandate that the it is part of a larger operation
which starts a transaction before calling the bean.
The transaction attribute Mandatory can be used when it is necessary to verify
the transaction association of the calling client. They reduce the composability
of a component by putting constraints on the calling client’s transaction
context.
28
Isolation Levels
Isolation Level
An isolation level defines how concurrent transactions to an enterprise information system are isolated
from one another. Enterprise information systems usually support the following the isolation levels:
• ReadCommitted - This level prevents a transaction from reading uncommitted changes from other
transactions.
• RepeatableRead - This level prevents a transaction from reading uncommitted changes from other
transactions. In addition, it ensures that reading the same data multiple times will receive the same value
even if another transaction modifies the data.
• Serializable - This level prevents a transaction from reading uncommitted changes from other
transactions and ensures that reading the same data multiple times will receive the same value even if
another transaction modifies the data. In addition, it ensures that if a query retrieves a result set based on
a predicate condition and another transaction inserts data that satisfy the predicate condition, re-execution
of the query will return the same result set.
Isolation level and concurrency are closely related. A lower isolation level typically allows greater
concurrency, at the expense of more complicated logic to deal with potential data inconsistencies. A
useful guideline is to use the highest isolation level provided by enterprise information systems that gives
acceptable performance.
For consistency, all enterprise information systems accessed by a J2EE application should use the same
isolation level. Currently, the J2EE specification does not define a standard way to set isolation levels
when an enterprise information system is accessed under JTA transactions.
29
Isolation
30
Isolation Level
Isolation Level
An isolation level defines how concurrent transactions to an enterprise information system are isolated
from one another. Enterprise information systems usually support the following the isolation levels:
• ReadCommitted - This level prevents a transaction from reading uncommitted changes from other
transactions.
• RepeatableRead - This level prevents a transaction from reading uncommitted changes from other
transactions. In addition, it ensures that reading the same data multiple times will receive the same value
even if another transaction modifies the data.
• Serializable - This level prevents a transaction from reading uncommitted changes from other
transactions and ensures that reading the same data multiple times will receive the same value even if
another transaction modifies the data. In addition, it ensures that if a query retrieves a result set based on
a predicate condition and another transaction inserts data that satisfy the predicate condition, re-execution
of the query will return the same result set.
Isolation level and concurrency are closely related. A lower isolation level typically allows greater
concurrency, at the expense of more complicated logic to deal with potential data inconsistencies. A
useful guideline is to use the highest isolation level provided by enterprise information systems that gives
acceptable performance.
For consistency, all enterprise information systems accessed by a J2EE application should use the same
isolation level. Currently, the J2EE specification does not define a standard way to set isolation levels
when an enterprise information system is accessed under JTA transactions.
31
Transaction Example
Transfer
Teller Account 1
1. Withdraw
Account 2
2. Deposit
32
Declarative Transaction Management
Example
Transfer Transaction
New Transaction Context propagated
Context
TC
Teller Account 1 TC
1. Withdraw
TX_REQUIRES_NEW TX_REQUIRED
Account 2 TC
Transaction 2. Deposit
Attributes TX_REQUIRED
33
ATM Transaction Example
34
EJBContext
javax.ejb
<<Interface>>
EJBContext
getEJBHome()
getCallerIdentity()
isCallerInRole()
getUserTransaction()
setRollBackOnly()
getRollBackOnly()
public abstract interface EJBContext The EJBContext interface provides an instance with access to the container-
provided runtime context of an enterprise Bean instance.
• The setRollbackOnly method allows the instance to mark the current transaction such that the only outcome of the
transaction is a rollback. Only instances of a session bean with container-managed transaction demarcation can use
this method.
•The getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback.
Only instances of a session bean with container-managed transaction demarcation can use this method.
35
Example without Transaction Control
try {
// Withdraw funds from account
fromAccount.withdraw(amount);
}
catch (Exception e) {
// If an error occurred, do not proceed.
}
try {
// Otherwise, deposit funds into account
toAccount.deposit(amount);
}
catch (Exception e) {
// If an error occurred, do not proceed,
// and redeposit the funds back into account
fromAccount.deposit(amount);
return;
}
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
36
Better Way: Container manages
transaction
try {
fromAccount.withdraw(amount);
toAccount.deposit(amount);
} catch(InsufficientFundsException ex) {
throw new InsufficientFundsException("Insufficient
funds " +
fromAcctId);
}
37
Rolling Back a Container-Managed
Transaction
public class AccountBean implements EntityBean {
// entity state
private double balance;
private int accountNumber;
// resources
private EntityContext context;
public void withdraw(double amount)throws InsufficientFundsException {
if( balance >= amount ) {
balance = balance - amount;
}
else {
context.setRollbackOnly();
throw new InsufficientFundsException (balance);
}
}
}
38
Transaction Management API
javax.transaction javax.ejb
<<Interface>>
<<Interface>>
UserTransaction
EJBContext
begin() getEJBHome()
commit() getCallerIdentity()
getStatus() isCallerInRole()
rollback() getUserTransaction()
setTransactionTimeout() setRollBackOnly()
setRollBackOnly() getRollBackOnly()
public abstract interface EJBContext The EJBContext interface provides an instance with access to the container-
provided runtime context of an enterprise Bean instance.
•The getUserTransaction method returns the javax.transaction.UserTransaction interface. The instance can use
this interface to demarcate transactions and to obtain transaction status. Only instances of a session bean with bean-
managed transaction demarcation can use this method.
The Java Transaction API, JTA, is implemented by the javax.transaction package.
javax.transaction.UserTransaction provides a high level client interface, which allows a bean client to manage the
scope of a transaction explicitly. Bean must have method transactional attributes set to TX_BEAN_MANAGED in
order to do this. Beans can use the EJBContext to get an UserTransaction object.
javax.transaction Interface UserTransaction The UserTransaction interface defines the methods that allow an
application to explicitly manage transaction boundaries.
void begin()
Create a new transaction and associate it with the current thread.
void commit()
Complete the transaction associated with the current thread.
int getStatus()
Obtain the status of the transaction associated with the current thread.
void rollback()
Roll back the transaction associated with the current thread.
void setRollbackOnly()
Modify the transaction associated with the current thread such that the only possible outcome of the transaction is to
roll back the transaction.
void setTransactionTimeout(int seconds)
Modify the value of the timeout value that is associated with the transactions started by the current thread with the
begin method.
39
JTA
•UserTransaction interface
–Enables application to demarcate transaction
boundaries
•begin, commit, getStatus,
getStatus, rollback,
rollback, setRollbackOnly,
setRollbackOnly,
setTransactionTimeout
–Exposed by application server
–Called by applications
–Implemented by transaction manager
javax.ejb.EJBContext.setRollbackOnly() method
An enterprise bean with container-managed transaction demarcation can use the setRollback-
Only() method of its EJBContext object to mark the transaction such that the transaction can
never commit. Typically, an enterprise bean marks a transaction for rollback to protect data
integrity before throwing an application exception, because application exceptions do not
automatically cause the Container to rollback the transaction. For example, an
AccountTransfer bean which debits one account and credits another account could mark a
transaction for rollback if it successfully performs the debit operation, but encounters a failure
during the credit operation.
javax.ejb.EJBContext.getRollbackOnly() method
An enterprise bean with container-managed transaction demarcation can use the getRollback-
Only() method of its EJBContext object to test if the current transaction has been marked for
roll-back. The transaction might have been marked for rollback by the enterprise bean itself,
by other enterprise beans, or by other components (outside of the EJB™ specification scope)
of the transaction processing infrastructure.
40
Explicit Transaction
Management Example
public class AtmBean implements SessionBean {
javax.ejb.SessionContext ejbContext;
javax.transaction.UserTransaction ut;
To demarcate a Bean Managed transaction, the bean uses JTA to invoke the
begin, commit, and rollback methods of the UserTransaction interface. The
code demonstrates the UserTransaction methods. The begin and commit
invocations delimit the updates to the database. If the updates fail, the code
invokes the rollback method and throws an EJBException.
41
Transaction Notification
javax.ejb
<<Interface>>
SessionSynchronization (can)
implement
afterBegin()
afterCompletion()
beforeCompletion()
xxxSessionBean
42
Session Synchronization
A container-managed session bean can optionally include session synchronization to manage the default
auto commit provided by the container. Session synchronization code lets the container notify the bean
when important points in the transaction are reached. Upon receiving the notification, the bean can take
any needed actions before the transaction proceeds to the next point.
SessionSynchronization interface
A session bean class can optionally implement the javax.ejb.SessionSynchronization interface. This
interface provides the session bean instances with transaction synchronization notifications. The instances
can use these notifications, for example, to manage database data they may cache within transactions.
The afterBegin notification signals a session bean instance that a new transaction has begun. The
container invokes this method before the first business method within a transaction (which is not
necessarily at the beginning of the transaction). The afterBegin notification is invoked with the transaction
context. The instance may do any database work it requires within the scope of the transaction.
The beforeCompletion notification is issued when a session bean instance’s client has completed work on
its current transaction but prior to committing the resource managers used by the instance. At this time, the
instance should write out any database updates it has cached. The instance can cause the transaction
to roll back by invoking the setRollbackOnly method on its session context.
The afterCompletion notification signals that the current transaction has completed. A completion status
of true indicates that the transaction has committed; a status of false indicates that a rollback has
occurred. Since a session bean instance’s conversational state is not transactional, it may need to
manually reset its state if a rollback occurred.
43
Stateful Session Bean
(With Transactions)
does not
exist
ejbRemove()
1) newInstance()
3)ejbCreate()
method-ready ejbPassivate()
EJB
passive
Instance ejbActivate()
business method
method-ready
In transaction
rollback commit
Transactional EJB
business method
Transaction Manager
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
44
Exercise: Implement Purchase Method
in ShoppingCart Bean
45
Transaction Exercise
EJB™ Container
Servlet Product Inventory
Shopping Deplete
Cart stock
Order Entry
create
order
EJB™ Server
46
ShoppingCartEJB™ OrderEJB
ShoppingCartEJB OrderEJB
cart orderId
numberOfItems orderLineItems
email
addItem () s ta tu s
deleteItem() totalPrice
clear() orderDate
getItems()
getOrderDetails()
getItem()
getNumberOfItems() creates ejb Create()
getTotal() ejb R e m o v e ( )
ejbCreate() s e t E n tityContext()
setSessionContext() ejb L o a d ()
ejbRemove() ejbStore()
ejbActivate() ejb FindByPrimaryK e y()
ejbPassivate() ejb Activate()
ejb P a s s ivate()
purchaseCart()
47
OrderEJB
Orders
OrderEJB
orderid o rde rId
email orderLineItems
date email
s ta tu s
ShipAddress totalPrice
Total price o rde rDate
1
getOrderDetails()
e jb Create()
e jb Re m ove()
0..n
setEnti tyContext()
e jb L o a d ()
OrderLineItem e jbStore()
orderId e jbFindByPrimaryK e y()
linenumber ejb Activate()
e jb P a s s ivate()
ISBN
quantity
Unit price
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
48
OrderEJB
<<Interface>>
Order
LineItem
getOrderDetails() OrderEJB
itemNo
orderId qty
orderLineItems unitPrice
email lineNo
s tatus
totalPrice getItemNo()
orderDate getQty()
<<Interface>> getUnitPrice()
OrderHome getOrderDetails() getLineNo()
orderId ejbCreate()
orderLineItems ejbRemove()
email setEntityContext()
orderDate ejbLoad()
status ejbStore()
totalPrice ejbFindByPrimaryKey() OrderDetails
ejbActivate() orderId
create() ejbPassivate() lineItems
findByPrimaryKey() email
orderDate
status
totalPrice
getOrderId()
getLineItems()
getEmail()
getOrderDate()
getStatus()
getTotalPrice()
49
Resources
• http://www.subrahmanyam.com/
• Wiley: Mastering Enterprise JavaBeans By Ed
Roman and JavaOne presentation
• O'REILLY: Enterprise JavaBeans By Richard
Monson-Haefel
• Programming with Enterprise JavaBeans, JTS,
and OTS by Andreas Vogel, Madhavan Rangarao
50