Transactions - PowerPoint PPT Presentation

1 / 53
About This Presentation
Title:

Transactions

Description:

Unit of work that accesses one or more shared resources (usually databases) ... Checking commited Results in TxClient. try { teller_.reset(from); teller_.reset(to) ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 54
Provided by: daniel85
Category:

less

Transcript and Presenter's Notes

Title: Transactions


1
Transactions
  • Source
  • Enterprise JavaBeans, 3rd Edition, Richard
    Monson-Haefel

2
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

3
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

4
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

5
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

6
Transaction Attributes
  • Supports Transactions
  • Supports_at_
  • Required
  • RequiresNew
  • Mandatory
  • Recommended for CMP 2.0 Entity Beans support
    required
  • Transactions not Supported
  • NotSupported_at_
  • Never_at_
  • _at_ support optional for CMP 2.0 Entity Beans

7
Setting the Declarative Transaction Attribute
  • ltejb-jargt
  • ...
  • ltassembly-descriptorgt
  • ltcontainer-transactiongt
  • ltmethodgt
  • ltejb-namegtAccountlt/ejb-namegt
  • ltmethod-namegtlt/method-namegt
  • lt/methodgt
  • lttrans-attributegtSupportslt/trans-attribut
    egt
  • lt/container-transactiongt
  • lt/assembly-descriptorgt
  • lt/ejb-jargt

8
Container and Beans
Home Interface
Container
Pool
Home
Home Stub
create
Client
Remote Object Stub
EJBObject
Account Bean
transfer
Remote Interface
9
Not Supported
Client
Invoked EJB
Thread of Execution
Clients 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

10
Supports
Client
Invoked EJB
(A)
(B)
Thread of Execution
Clients Transaction Context
No Transaction Context
  • 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)

11
Required
Client
Invoked EJB
(A)
(B)
Thread of Execution
Clients Transaction Context
  • Joins the transaction context if invoked as part
    of a transaction (A)
  • Initiates its own transaction context of invoked
    outside of a transaction (B)

12
RequiresNew
Client
Invoked EJB
(A)
(B)
Thread of Execution
Clients Transaction Context
  • 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

13
Mandatory
Client
Invoked EJB
(A)
(B)
Transaction Exception
Thread of Execution
Clients Transaction Context
  • 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)

14
Never
Client
Invoked EJB
(A)
Transaction Exception
(B)
Thread of Execution
Clients Transaction Context
  • 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)

15
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

16
Database Locks
  • How do you prevent overlapping transactions from
    viewing the others 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

17
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

18
Specifying Isolation Level
  • ltweblogic-ejb-jargt
  • lttransaction-isolationgt
  • lt!-- TRANSACTION_SERIALIZABLE
  • TRANSACTION_READ_COMMITTED
  • TRANSACTION_READ_UNCOMMITTED
  • TRANSACTION_REPEATABLE_READ
  • --gt
  • ltisolation-levelgtTRANSACTION_READ_COMMITTEDlt
    /isolation-levelgt
  • ltmethodgt
  • ltejb-namegtAccountlt/ejb-namegt
  • ltmethod-namegtlt/method-namegt
  • ltmethodgt
  • lt/transaction-isolationgt

19
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

20
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()

21
CMR and Transactions
  • Collections obtained through CMR must be accessed
    within the same transaction
  • public void processAccounts(CustomerLocal
    customer)
  • Collection accounts customer.getAccounts()
  • for (Iterator iaccounts.iterator()
    i.hasNext() )
  • processAccounts must have a transaction context
    active or will receive a java.lang.IllegalStateExc
    eption when accessing accounts

22
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

23
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) gt 0)
    setBalance(balance - amount)
  • else
  • setBalance(balance - 1.0F) //subtract
    fee
  • throw new AccountException("overdraw")
  • ...

24
TellerEJB
  • public 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

25
TxClient Initialization
  • fromAccounts_ new Hashtable(LAST_TYPE)
  • toAccounts_ new Hashtable(LAST_TYPE)
  • for(int iFIRST_TYPE iltLAST_TYPE i)
  • String id uidGenerator_.createUID().toString()
  • AccountRemote account createAccount(TX_TYPEi
    , id)
  • toAccounts_.put(TX_TYPEi, account)
  • id uidGenerator_.createUID().toString()
  • account createAccount(TX_TYPEi, id)
  • fromAccounts_.put(TX_TYPEi, account)

26
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())

27
TxClient Execution
  • private static void execute(final Context jndi)
    throws Exception
  • TxClient client new TxClient(jndi)
  • for(int iFIRST_TYPE iltLAST_TYPE i)
  • for(int jFIRST_TYPE jltLAST_TYPE j)
  • System.out.println(TX_TYPEi "-gt"
    TX_TYPEj)
  • client.transfer(i,j)

28
Running the Example
  • Deploy the EJB/EAR
  • corej2ee.bash txBankApp init
  • Run the Client
  • corej2ee.bash txBankApp

29
TxClient Output
  • NotSupported-gtNotSupported
  • transfer failed overdrawfrom(19197 )-1.0,
    to(19196 )5.0
  • NotSupported-gtSupports
  • transfer failed overdrawfrom(19197 )-1.0,
    to(19198 )0.0
  • NotSupported-gtRequiresNew
  • transfer failed overdrawfrom(19197 )-1.0,
    to(19200 )5.0
  • Supports-gtNotSupported
  • transfer failed overdrawfrom(19199 )0.0,
    to(19196 )5.0
  • Supports-gtSupports
  • transfer failed overdrawfrom(19199 )0.0,
    to(19198 )0.0
  • Supports-gtRequiresNew
  • transfer failed overdrawfrom(19199 )0.0,
    to(19200 )5.0

30
TxClient Output
  • RequiresNew-gtNotSupported
  • transfer failed overdrawfrom(19201 )-1.0,
    to(19196 )5.0
  • RequiresNew-gtSupports
  • transfer failed overdrawfrom(19201 )-1.0,
    to(19198 )0.0
  • RequiresNew-gtRequiresNew
  • transfer failed overdrawfrom(19201 )-1.0,
    to(19200 )5.0
  • ltAdditional Outputgt
  • DEFAULT-gtDEFAULT
  • transfer failed overdrawfrom(19203 )0.0,
    to(19202 )0.0

31
Managing the transfer() Transaction Context
5 register toAccountEJB
Supports
TxClient
toAccountEJB
4 deposit
Required
TellerEJB
Supports
7 withdraw
1 transfer()
fromAccountEJB
2 register TellerEJB
10 verify all will work
8 register fromAccountEJB
Transaction Manager
11 commit or rollback all updates
6 add toAccountEJB
  • Transaction Context
  • TellerEJB
  • toAccountEJB
  • fromAccountEJB

3 create tx context add TellerEJB
9 add fromAccountEJB
32
Distributed Tx ArchitectureTwo Phase Commit
(2-PC/TPC)
Transaction Coordinator
Resource Manager
1. Prepare to Commit
TX Manager
2. Return
4. commit
Resource Manager
TX Manager
5. return
3. Log Result
33
Resource Managers
  • Examples
  • JDBC Drivers
  • JMS Provider

34
Adding 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

35
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")

36
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")

37
TxClient Output with Two Resource Managers
  • //note that resets received expected messages
  • NotSupported-gtNotSupported
  • transfer failed overdrawfrom(19205 )-1.0,
    to(19204 )5.0no message
  • NotSupported-gtSupports
  • transfer failed overdrawfrom(19205 )-1.0,
    to(19206 )0.0no message
  • NotSupported-gtRequiresNew
  • transfer failed overdrawfrom(19205 )-1.0,
    to(19208 )5.0no message
  • Supports-gtNotSupported
  • transfer failed overdrawfrom(19207 )0.0,
    to(19204 )5.0no message
  • Supports-gtSupports
  • transfer failed overdrawfrom(19207 )0.0,
    to(19206 )0.0no message
  • Supports-gtRequiresNew
  • transfer failed overdrawfrom(19207 )0.0,
    to(19208 )5.0no message

38
TxClient Output with Two Resource Managers
  • RequiresNew-gtNotSupported
  • transfer failed overdrawfrom(19209 )-1.0,
    to(19204 )5.0no message
  • RequiresNew-gtSupports
  • transfer failed overdrawfrom(19209 )-1.0,
    to(19206 )0.0no message
  • RequiresNew-gtRequiresNew
  • transfer failed overdrawfrom(19209 )-1.0,
    to(19208 )5.0no message
  • //extra output
  • DEFAULT-gtDEFAULT
  • transfer failed overdrawfrom(19211 )0.0,
    to(19210 )0.0no message

39
Enable 2PC Transactions for Connection Pool
40
Enable JTS Transactions in Entity Bean
  • ltweblogic-rdbms-jargt
  • ltweblogic-rdbms-beangt
  • ltejb-namegtAccountlt/ejb-namegt
  • ltdata-source-namegtcorej2ee.jdbc.corej2eeTxDSlt/
    data-source-namegt
  • lttable-mapgt
  • lttable-namegttxbank_Accountlt/table-namegt

41
Enable JTS Transactions for JMS
42
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

43
Stateful 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

44
SessionSynchronization Example
  • public class SessionSynchronizedTellerEJB
  • implements SessionBean, javax.ejb.SessionSynchr
    onization
  • 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)

45
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)

46
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

47
User Transaction
48
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()

49
Programmatic Transactions in EJB
  • Allowed in Session Beans
  • ltsessiongt
  • ...
  • lttransaction-typegtBeanlt/transaction-typegt
  • 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

50
Transactional Clients
  • End user can also control transactions
  • UserTransaction ut (UserTransaction)
    jndiContext.lookup(javax.transaction.UserTransact
    ion)
  • ut.begin()
  • // perform multiple operations on beans
  • account1.deposit( 34 )
  • account2.withdraw( 34 )
  • ut.commit()

51
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

52
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

53
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
Write a Comment
User Comments (0)
About PowerShow.com