Transactions - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Transactions

Description:

Two way to handle another transaction at the same time. ... The user changes widget's attributes and submits the changes along with the version identifier ... – PowerPoint PPT presentation

Number of Views:291
Avg rating:3.0/5.0
Slides: 44
Provided by: Computer105
Category:

less

Transcript and Presenter's Notes

Title: Transactions


1
Transactions
  • Presenters
  • Jin Young Ahn, Sowjanya Chava
  • Towson University

2
Topics
  • Overview of transaction terminology including
    ACID properties and transaction isolation levels
    as well as the concepts of local and distributed
    transactions.
  • Describes various distributed transaction
    scenarios
  • The programmatic transaction model provided by
    the JTA
  • Describes the declarative transaction model used
    with J2EE component

3
Transaction Overview
  • Transaction is a unit of work, a sequence of
    operation that succeed or fail as a single unit.
  • Transactions work closely with one or more
    resources.
  • A transaction does not directly interact with a
    resource.
  • A resource manager manages the resource. The
    transaction is coordinated with the resource
    managers using a transaction manager, also known
    as a transaction processing (TP) monitor.
  • The transaction manager works by passing the
    same transaction context to the different
    resource managers participating in the
    transaction. The transaction manager keeps
    transaction logs of the work it has asked the
    resource manager to do.

4
Transaction Properties
  • Transactions have for main properties, referred
    to as ACID properties.
  • Atomic
  • Implies that the transaction is a unit of work
    consisting of many operations as a single unite
    nd that it succeeds or fails as one unit of work.
  • Consistent
  • Means that the effect of the transaction should
    leave the system in a knows and stable state.
  • Isolated
  • Implies that transactions do not intersperse
    intermediated updates with other transactions.
  • Durable
  • Means that the effects of a transaction persist.

5
Transaction Isolation Problems
  • Isolation, the I in ACID, can have various
    levels.
  • Dirty read
  • A dirty read occurs when a transaction reads data
    that another transaction has changed but not yet
    committed.
  • Nonrepeatable read
  • The same transaction reads the same data twice
    with different results.
  • Phantom read
  • You read data, look again, and it is gone, or
    when you read data, look again, and new data
    suddenly appears.

6
Transaction Isolation Levels
Table 16-1 Transaction isolation violation and
levels
  • During the users update/insert the data
    concurrently, it should guarantee Data
    Consistency, Data Concurrency
  • Should you always select serializable? No !
  • Because transaction isolation level and
    concurrency are inversely related. Need to find
    out a balance between the safety of higher
    isolation levels and the greater performance
    possible at lower isolation level.

7
Transaction Model
  • Flat transaction model (FTM)
  • Only one transaction is active at any given time.
  • lt Two way to handle another transaction at the
    same time. gt
  • 1) You can disallow starting another transaction.
  • 2) Suspend the current transaction, start new one
    transaction. Once, new transaction finished, the
    original transaction resume.
  • Nested transaction model (NTM)
  • Transaction are nested, forming a tree of
    transactions with multiple transaction active at
    the same time.

8
Distributed Transactions
  • Local transaction is a transaction that
    communicates with just one resource with no
    transaction monitor involved.
  • Distributed or Global transaction is a
    transaction that covers multiple resource
    managers and is coordinated by a transaction
    monitor.

9
Distributed Transactions Scenario(1,2)
Figure 16-3 Database and message queue
(1) A transaction spans a database and a message
queue. The most common distributed transactions
in J2EE application.0
Queue M
Server P Component A
Client
Customer Database
Server P Component A
Client
(2) A transaction spans two databases. Both
operations are part of the same distributed
transaction.
Order Database
Figure 16-4 Multiple database
10
Distributed Transactions Scenario(3,4)
Figure 16-5 Multiple application server
(3) A transaction spans two different application
server instances.
Server P Component A
Client
Server Q Component B
Server P
Component A
(4) The client start a transaction. The client
then invokes components running on one or more
application server. The client container
propagates the transaction to the various
components that the client invokes.
Client
Component B
Figure 16-6 Client demarcation
11
Two-Phase Commit
  • Two-Phase commit is the protocol used to
    implement distributed transactions between
    different resource managers.
  • lt Two distinct phases in the two-phase commit
    protocol gt
  • Prepare Phases
  • The transaction manager sends a prepare (to
    commit) message to every resource participating
    in the transaction. Each resource replies back
    with either a ready response or an abort
    response.
  • In the second phases, if all ready, transaction
    manager commits, otherwise rollback.
  • Commit phases or rollback phases.

12
Two-Phase Commit
Application
Transaction
Transaction Manager
Resource Manager1
Resource Manager2
begin
begin
Do the work

commit
prepare
commit
prepare
ready
abort
roll back
Figure 16-7 Rollback in the first phase of a
two-phase commit
13
Two-Phase Commit
Application
Transaction
Transaction Manager
Resource Manager1
Resource Manager2
begin
begin
Do the work

commit
prepare
commit
prepare
ready
ready
commit
commit
Figure 16-8 Successful commit in two-phase commit
14
Programmatic Transactions versus Declarative
Transactions
  • Transactions can be coded in two ways
  • Programmatically
  • Declaratively
  • Programmatic transactions is the hard coding of
    transaction management within the application
    code
  • Declarative transaction management refers to
    non-programmatic approach i.e. transactional
    behavior can be controlled using deployment
    descriptor

15
Programmatic Transactions
  • A programmatic transaction may be either a JDBC
    or JTA transaction
  • If the application requires distributed
    transactions then transaction code is implemented
    using JTA
  • Application code begins a transaction against
    resource managers (databases, message servers,
    EJB components)
  • At some point application decides whether to
    rollback or commit the transaction
  • Container propagates the transactional context to
    different components and resources that client
    uses
  • JTA exposes these capabilities to applications
    through javax.transaction.UserTransaction
    interface

16
Programmatic Transactions
  • JTA client acquires a UserTransaction from
    transaction manager through JNDI lookup using
    javacomp/UserTransaction
  • Once client has UserTransaction, transaction is
    explicitly started by using begin() method of
    javax.transaction.UserTransaction instance
  • Transaction is committed by commit() method and
    rolled back by rollback() method of
    UserTransaction
  • If transaction manager supports nested
    transactions, user can begin a transaction by
    begin() on the UserTransaction before committing
    or rolling back current transaction
  • If the transaction manager doesnt support nested
    transactions, attempting to create a nested
    transaction will result in javax.transaction.NotSu
    pportedException

17
Programmatic Transactions
  • Example Client-managed transaction demarcation
  • InitialContext aInitialContext new
    InitialContext()
  • UserTransaction aUserTrancation
    (UserTranscation) aInitialContext.lookup(
    javacomp/UserTransaction)
  • try
  • aUserTransaction.begin()
  • PersonHome aPersonHome (PersonHome)
    aInitialContext.lookup( javacomp/env/ejb/Person
    )
  • Person p aPersonHome.create( aPersonValue.getEmai
    l(), aPersonValue.getPassword())
  • p.setWorkPhone(aPersonValue.getWorkPhone())
  • p.setWorkPhone(aPersonValue.getHomePhone())
  • sLogger.info( created a person with id
    p.getPersonID())

18
Programmatic Transactions
  • aUserTranscation.commit()
  • catch ( Exception e)
  • try
  • aUserTranscation.rollback()
  • catch (Exception aException)
  • String aMessage Exception occurred in client
    command.execute rollback
  • sLogger.log (Level. SEVERE, aMessage,
    aException)
  • throw aException
  • String aMessage Exception occurred in client
    command. execute
  • sLogger.log ( Level. SEVERE, aMessage, e)
  • throw e

19
Declarative Transactions
  • Component deployment descriptor is responsible
    for whole transaction management (begin, suspend,
    commit or roll back)
  • Declarative transaction management can include
    transactional parameters such as isolation levels
  • This facilities are available in EJB deployment
    descriptors
  • It separates business logic from transaction code
  • Applications that have declarative transaction
    management are much easier to maintain and evolve
  • All the complexity of transaction management is
    ceded to transaction manager leaving business
    related code in the application
  • In some circumstances declarative transactions
    are inefficient and programmatic transactions are
    required

20
Optimistic Concurrency
  • Consider the following Example
  • A user selects a widget to edit
  • The application displays details about the widget
    for editing
  • This process involves two distinct transactions
  • The application obtains the widget for the user
    to edit in the first transaction
  • The application updates the widget in the
    database using a second transaction, committing
    first users changes
  • What if another user edited the same widget
    before the second transaction of first user
    committed

21
Optimistic Concurrency
  • The second users changes are lost, this type of
    application behavior is known as last
    update/write wins policy or lost update problem
  • Transaction isolation levels does not solve the
    problem because they are useful for concurrent
    transactions
  • One simple solution to this problem is optimistic
    concurrency i.e. before every update check
    whether the data is not updated by another
    transaction
  • One way to implement this is using a version
    identifier
  • Application also keeps track of version
    identifier associated with the widget using a
    field in the relational database

22
Optimistic Concurrency
  • The user changes widgets attributes and submits
    the changes along with the version identifier
  • The changes are successful when the submitted
    version identifier matches the version identifier
    in the database
  • Upon successful update version identifier is
    incremented
  • If the second user changes the data before the
    first user committed its changes, the action of
    the second user increments the version identifier
    and when first user tries to submit the changes
    the application rejects the changes, since there
    is no match in version identifiers

23
Optimistic Concurrency
  • This technique prevents the first user from
    overriding the changes made by the second user
  • The first user state is as-is and is asked to
    submit the changes again
  • Other techinques are using timestamp, checksum
    and checking all the data in the previous row
  • This technique is optimistic because the
    likelihood of conflict is minimal by splitting
    its operations into two separate independent
    transactions

24
EJB Transaction Management
  • If declarative transaction management is used in
    EJBs this is referred as Container-Managed
    Transaction Demarcation (CMTD)
  • The container is responsible for starting,
    committing and rolling back transactions required
    by the EJB
  • These are specified in the deployment descriptor
    or programmatic hints in the developers EJB code
  • Container uses JTA for transaction management
  • Programmatic transaction management within EJB
    components is known as Bean-Managed Transaction
    Demarcation (BMTD)
  • The transaction operations are performed through
    resource-specific APIs (JDBC,JMS or JTA)

25
BMTD with JTA
  • Bean-managed transaction doesnt use only JTA
    calls it can also use JDBC/JMS
  • If we need to use JTA, then the JTA transaction
    can be obtained from JNDI context of the EJB
    container. EJB allows us to access the
    UserTransaction using
  • getUserTransaction() method of
    javax.ejb.EJBContext
  • Example Accessing the UserTransaction from
    EJBContext
  • SessionContext mSessionContext.
  • UserTransaction aUserTransaction
    mSessionContext.getUserTransaction()

26
BMTD with JTA
  • If we are using JTA API to manage transaction
    boundaries, the specification prohibits invoking
    resource-specific APIs
  • The EJB specification prohibits invoking
  • Commit() or rollback() methods of
  • java.sql.Connection interface and
  • javax.jms.Session interface
  • getRollbackOnly() and setRollbackOnly()
  • methods of javax.ejb.EJBContext

27
Stateless session beans and message-driven
beans
  • By definition the stateless session bean does not
    maintain state information of the client
  • The bean method that starts the transaction must
    complete the transaction by calling commit() or
    rollback() method.
  • If we fail to do so, the container rolls back the
    transaction and throws an exception
    (java.rmi.RemoteException for remote clients and
    javax.ejb.EJBException for local clients)

28
Stateless session beans and message-driven
beans
  • If we start a transaction in the onMessage()
    method of a message-driven bean with BMTD, we
    must call the commit() or rollback() method with
    in the on Message() method to complete the
    transaction
  • if its not done this way then the container rolls
    back the transaction and discards the instance of
    the bean
  • No exception is thrown back to the client,
    because client indirectly invoked the bean by
    sending a message

29
Stateful session bean
  • Unlike the stateless session bean the sate
    remains across subsequent method calls
  • The transaction remains in effect for the bean
    until the commit() or rollback() method is called
  • As long as the transaction started by the bean is
    active all requests made by clients will operate
    under this transaction context until it is
    committed or rolled back

30
Container-Managed Transaction Demarcation (CMTD)
  • If a EJB is using CMTD then it is prohibited from
    using JTA operations in any contexts in which it
    might interfere with containers transaction
    management activities
  • It must not invoke getUserTransaction() method of
    javax.ejb.EJBContext
  • If it does then container will throw a
    java.lang.IllegalstateException
  • It must not invoke UserTransaction methods,
    message listener callbacks or ejbTimeout()
    callbacks
  • The bean is forbidden from calling commit() or
    rollback() on JDBC connection or JMS session

31
Inducing rollbacks in CMTD
  • Though application code is not allowed to
    directly interface with transaction management
    under CMTD, EJB can induce rollback by calling
    setRollbackOnly() method of javax.ejb.EJBContext
  • At the end of the transaction the container
    automatically rollbacks the transaction
    regardless of the state of transaction
  • We can know whether the current transaction is
    marked for rollback by calling getRollbackOnly()
    method of EJBContext
  • The container will also roll back a transaction
    when the EJB code throws a runtime exception
    javax.ejb.EJBException

32
Some common programming scenarios
  • Below are some of the common transaction
    scenarios to leverage transactions effectively
  • Using a Session Façade facilitates to use CMTD
    effectively with an EJB component by minimizing
    the number of unnecessary transactions and
    increasing performance
  • Using Transaction Attributes with CMTD
    illustrates an approach for utilizing transaction
    attributes with CMTD EJBs. Helps to avoid
    resorting to BMTD in some situations
  • Distributed Transactions Involving a JMS
    Destination and Database deals with distributed
    transaction using both JMS and JDBC resources

33
Using a Session Facade
  • In the previous example
  • If EJB has been deployed with a Required
    transaction attribute that applies to all the
    methods
  • Each EJB method create(), setWorkPhone(),
    setHomePhone() and getPersonID() is invoked in
    different transaction
  • This is not the intended behavior and the code is
    not only very expensive but may be incorrect

34
Using a Session Facade
  • The solution to this problem is using the session
    façade pattern
  • This pattern involves a stateless session bean
  • Change the code from the client into a stateless
    session bean
  • This is deployed using Required transaction
    attribute on its methods
  • create(), setWorkPhone(), setHomePhone() and
    getPersonID() are invoked in one single
    transaction

35
Using a Session Facade
  • Example Code fragment from session façade
  • public PersonValue createPersonSameTransaction(
    PersonValue aPersonValue)
  • return createPerson (aPersonValue)
  • Protected PersonValue createPerson (PersonValue
    aPersonValue)
  • sLogger.info(5 creating person in manager cmtd
    bean)
  • try
  • InitialContext aInitialContext new
    InitialContext()
  • PersonHome aPersonHome (PersonHome)
    aInitialContext.lookup( javacomp/env/ejb/Person
    )

36
Using a Session Facade
  • Person p aPersonHome.create( aPersonValue.getEmai
    l(), aPersonValue.getPassword())
  • p.setWorkPhone(aPersonValue.getWorkPhone())
  • p.setWorkPhone(aPersonValue.getHomePhone())
  • sLogger.info( created a person with id
    p.getPersonID())
  • catch ( Exception e)
  • String aMessage Exception in manager cmtd
    bean.createPersonNewTransaction
  • sLogger.log ( Level. SEVERE, aMessage, e)
  • throw new EJBException (aMessage e)
  • return aPersonValue

37
Using Transaction Attributes with CMTD
  • Consider a simple object model there is a person
    EJB and a PersonStatus bean
  • Create person with PersonStatus, Person should
    succeed regardless of whether the PersonStatus is
    valid
  • Example Create Person and PersonStatus
  • public PersonValue createPersonAndStatus(
  • personValue aPersonValue,
  • personStatusValue aPersonStatusValue)
  • aPersonValue createPersonNewTransaction(aPersonV
    alue)
  • aPersonStatusValue createPersonStatus(
    aPersonValue, aPersonstatusValue)
  • return aPersonValue

38
Using Transaction Attributes with CMTD
  • If the bean is using CMTD and if we want to
    enforce some requirements
  • Set the transaction attribute for the
    createPersonAndStatus() method as Required
  • Set the transaction attribute for the
    createPersonNewTransaction() method as
    RequiredNew
  • We would expect that this would cause a new
    transaction suspending the one on the
    createPersonAndStatus()
  • But the same transaction is used for both the
    methods, because it never has an opportunity to
    intercept the second method call and start a new
    transaction

39
Using Transaction Attributes with CMTD
  • Example Create Person with interception
  • public PersonValue createPersonAndStatusNew(
  • personValue aPersonValue,
  • personStatusValue aPersonStatusValue) throws
    RemoteException
  • aPersonValue ((ManagerCMTD) msessionContex
    t.getEJBObject()).
  • createPersonNewTransaction(
    aPersonValue)
  • aPersonStatusValue createPersonStatus(
    aPersonValue, aPersonstatusValue)
  • return aPersonValue

40
Distributed Transactions Involving a JMS
Destination and Database
  • Fig Distributed Transaction

CreatePersonBean (MDB)
ManagerCMTD Stateless Session Bean
Person (Entity Bean)
Message
Database
Person Queue
41
Distributed Transactions Involving a JMS
Destination and Database
  • An instance of a message driven bean,
    CreatePersonBean retrieves message from Person
    Queue
  • The message is of type javax.jms.ObjectMessage
  • In the onMessage() callback, message driven bean
    retrieves an instance of personValue from the
    object message
  • The bean invokes the createPersonSameTransaction()
    on managerCMTD stateless session bean
  • The managerCMTD bean send the data to the
    database using the person entity bean

42
Transaction Best Practices
  • Use declarative transaction management rather
    than programmatic transaction management
  • When using declarative transactions with EJBs,
    use Required as the first choice for a
    transaction attribute
  • Avoid mixing direct transaction management using
    JTA with implicit transaction management done
    through specific API such as JDBC or JMS
  • Minimize the use of client-managed transactions
    whenever possible. The session-façade can be
    useful
  • Carefully evaluate the need and implementation of
    an optimistic concurrency strategy
  • Transactions help us to manage very complex and
    even unpredictable behavior when dealing with
    shared network resources

43
  • Questions?
Write a Comment
User Comments (0)
About PowerShow.com