Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enterprise Java v121030Java EE Transactions1. Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be.

Similar presentations


Presentation on theme: "Enterprise Java v121030Java EE Transactions1. Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be."— Presentation transcript:

1 Enterprise Java v121030Java EE Transactions1

2 Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be able to define transaction scope and properties within the EJB Tier

3 Enterprise Java v121030Java EE Transactions3 Objectives Transaction Overview Transaction Scope Class Annotations and XML Descriptors SessionSynchronization Transaction Propagation Isolation Issues Database Locks Isolation Levels Programmatic and Optimistic Locking Bean Managed Transactions Exceptions and Transactions

4 Enterprise Java v121030Java EE Transactions4 Transactions 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

5 Enterprise Java v121030Java EE Transactions5 Transaction ACID 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

6 Enterprise Java v121030Java EE Transactions6 EJB Transaction Support Declarative –transaction management controlled through deployment descriptor Programmatic –direct programming calls –transaction management code mixed with business code change in transactional behavior requires change in business code

7 Enterprise Java v121030Java EE Transactions7 Transaction Scope javax.ejb.TransactionAttributeType ** MANDATORY –tx must be active before calling ** REQUIRED –tx will be created if not active ** REQUIRES_NEW –new tx will created, no matter what SUPPORTS –will join active transaction, but won't create one NOT_SUPPORTED –won't join active transaction and won't create one NEVER –tx must not be active when calling ** EJB3 strongly advises EntityManagers accessed within the scope of a JTA transaction; use one of these 3 for wrapping JPA implementations

8 Enterprise Java v121030Java EE Transactions8 Defining Transaction Attributes: Java Annotations Defining global default for EJB @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) public class HotelRegistrationEJB implements HotelRegistrationRemote, HotelRegistrationLocal { Defining override for specific EJB method @Stateful @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class AgentReservationSessionEJB implements... {... @TransactionAttribute(TransactionAttributeType.REQUIRED) public Booking commit() throws AgentReservationException {... }

9 Enterprise Java v121030Java EE Transactions9 Defining Transaction Attributes: ejb-jar.xml Defining a default for the EJB HotelRegistrationEJB... HotelRegistrationEJB * Required

10 Enterprise Java v121030Java EE Transactions10 Defining Transaction Attributes: ejb-jar.xml Defining a override for specific EJB method HotelReservationSessionEJB * NotSupported HotelReservationSessionEJB commit Required

11 Enterprise Java v121030Java EE Transactions11 Transaction Scope Determines whether –transaction must exist –transaction is started –transaction is adopted –transaction is ignored –transaction can't exist

12 Enterprise Java v121030Java EE Transactions12 Not Supported Invoked EJB Client 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

13 Enterprise Java v121030Java EE Transactions13 Supports Invoked EJB Client 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)

14 Enterprise Java v121030Java EE Transactions14 Required Invoked EJB Client 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

15 Enterprise Java v121030Java EE Transactions15 RequiresNew Invoked EJB Client 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

16 Enterprise Java v121030Java EE Transactions16 Mandatory Invoked EJB Client 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

17 Enterprise Java v121030Java EE Transactions17 Never Invoked EJB Client 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

18 Enterprise Java v121030Java EE Transactions18 Scenario: Transaction Scope Client Creates 9 Valid and 1 Invalid Reservation HotelReservationSessionRemote session = //jndi.lookup for(int i=0; i<9; i++) { session.createReservation(person, startTime, endTime); } //now create a bad one session.createReservation(person, endTime, startTime); Client requests to EJB to complete all Reservations try { session.commit(); } catch (InvalidParameterException ex) {... } HotelRegistrationRemote reservationist = //jndi.lookup List mine = reservationist.getReservationsForPerson(person, 0, 100); if (mine.size() == 0) { log.info("all reservations were rolled back for: " + key); } else { log.info("" + mine.size() + " reservations were not rolled back for: " + key); }

19 Enterprise Java v121030Java EE Transactions19 Scenario: One Propogated Transaction Calling EJB Starts Tx @Stateful @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class AgentReservationSessionEJB implements... { @TransactionAttribute(TransactionAttributeType.REQUIRED) public Booking commit() throws AgentReservationException { /* for loop */ reservationist.createReservation( p.getPerson(), p.getStartDate(), p.getEndDate()); } Called EJB Requires a Tx; willing to take existing @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) public class HotelRegistrationEJB implements... { public Reservation createReservation(...) throws HotelReservationException { if (startDate == null) { throw new InvalidParameterException(...); }

20 Enterprise Java v121030Java EE Transactions20 Sample Result This one was specifically configured with REQUIRED -*** testBadCreates:RequiredSessionEJB *** -got expected exception:ejava.examples.txhotel.bl.InvalidParameterException: start date after end date -all reservations were rolled back for: RequiredSessionEJB This one is one took the defaults -*** testBadCreates:HotelReservationSessionEJB *** -got expected exception:ejava.examples.txhotel.bl.InvalidParameterException: start date after end date -all reservations were rolled back for: HotelReservationSessionEJB

21 Enterprise Java v121030Java EE Transactions21 Scenario: New Transactions Calling EJB Starts Tx @Stateful @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class AgentReservationSessionEJB implements... { @TransactionAttribute(TransactionAttributeType.REQUIRED) public Booking commit() throws AgentReservationException { /* for loop */ reservationist.createReservation( p.getPerson(), p.getStartDate(), p.getEndDate()); } Called EJB Requires a Tx; willing to take existing @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public class HotelRegistrationEJB implements... { public Reservation createReservation(...) throws HotelReservationException { if (startDate == null) { throw new InvalidParameterException(...); }

22 Enterprise Java v121030Java EE Transactions22 Scenario: One Propogated Transaction Configured with REQUIRES_NEW -*** testBadCreates:RequiresNewSessionEJB *** -got expected exception:ejava.examples.txhotel.bl.InvalidParameterException: start date after end date -9 reservations were not rolled back for: RequiresNewSessionEJB

23 Enterprise Java v121030Java EE Transactions23 Transaction Propogation

24 Enterprise Java v121030Java EE Transactions24 Persistence ContextTransaction Propogation Tx-scoped Entity Manager called outside of Tx –creates transaction on entry –creates a new tx-scoped persistence context –commits transaction and detaches entities on exit Tx-scoped Entity Manager called with active Tx –creates new tx-scoped persistence context if needed –uses existing persistence context if present i.e., persistence context passed from EJB to EJB within Tx Exception thrown if persistence context passed to Stateful Session Bean using extended entity manager Extended persistence context from Stateful Session Bean is passed to tx- scoped Entity Managers when Stateless Session Bean called –Stateful Session Beans may only share extended persistence contexts with Stateful Session Beans injected by the container Persistence Contexts do not cross Tx scope boundaries

25 Enterprise Java v121030Java EE Transactions25 SessionSynchronization Stateful Session Bean –contain client state similar in concept to HttpSession –state may be tx-sensitive –may receive transaction lifecycle events unlike HttpSession

26 Enterprise Java v121030Java EE Transactions26 SessionSynchronization @Stateful public class HotelReservationSessionEJB implements HotelReservationSessionLocal, HotelReservationSessionRemote, javax.ejb.SessionSynchronization { public void afterBegin() { log.debug("*** Transaction Started ***"); } public void beforeCompletion() throws EJBException, RemoteException { log.debug("*** Transaction about to complete ***"); } public void afterCompletion(boolean status) { log.debug("*** Transaction Completed:" + status + " ***"); }

27 Enterprise Java v121030Java EE Transactions27 SessionSynchronization [HotelReservationSessionEJB] *** HotelReservationSessionEJB *** [HotelReservationSessionEJB] ctx=org.jboss.ejb3.BaseSessionContext@ef27e3 [HotelReservationSessionEJB] reservationist=RequiresNewEJB [HotelReservationSessionEJB] *** Transaction Started *** [HotelReservationSessionImpl] ************ creating 10 reservations *** [HotelReservationSessionEJB] *** Transaction about to complete *** [HotelReservationSessionEJB] *** Transaction Completed:true *** [HotelReservationSessionEJB] *** HotelReservationSessionEJB closing *** [HotelReservationSessionEJB] *** HotelReservationSessionEJB *** [HotelReservationSessionEJB] ctx=org.jboss.ejb3.BaseSessionContext@11de6a0 [HotelReservationSessionEJB] reservationist=HotelRegistrationEJB [HotelReservationSessionEJB] *** Transaction Started *** [HotelReservationSessionImpl] ************ creating 10 reservations *** [HotelRegistrationEJB] error creating reservation, rolling back transaction:start date after end date [HotelReservationSessionEJB] *** Transaction Completed:false *** [HotelReservationSessionEJB] *** HotelReservationSessionEJB closing ***

28 Enterprise Java v121030Java EE Transactions28 Transaction Isolation 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

29 Enterprise Java v121030Java EE Transactions29 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

30 Enterprise Java v121030Java EE Transactions30 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

31 Enterprise Java v121030Java EE Transactions31 Locking Programmatic Locking –EntityManager.lock(object, LockModeType) LockModeType.READ LockModeType.WRITE –Constrains system to work sequentially on locked resources –Bottleneck –Vendors not required to support unless @Version field supplied Optimistic Locking –Permits parallel processing of information –Assumes that conflicts rarely occur –Error correction occurs after conflict detected

32 Enterprise Java v121030Java EE Transactions32 Optimistic Locking Problem Client requests a Reservation Reservation reservation = new Reservation(...); em.persist(em); return reservation; A second client request obtains another copy return em.find(Reservation.class, id); The first client makes a change reservation.setStartDate(...) The second client makes a change reservation.setCost(...) The first client change is made on server em.merge(reservation) The second client change is made on server em.merge(reservation) Impact, the first client change is lost

33 Enterprise Java v121030Java EE Transactions33 javax.persistence Support Add a version field to the class and annotate public class Reservation implements Serializable { @Id private long id; @Version private long version; private String confirmation; private Date startDate; private Date endDate; private Person person; Or provide metadata about existing field <entity class="ejava.examples.txhotel.bo.Reservation"

34 Enterprise Java v121030Java EE Transactions34 javax.persistence Support EntityManager will check whether update is using current version of class or will throw exception reservation.setVersion(version - 1); start.add(Calendar.DAY_OF_YEAR, 1); reservation.setStartDate(start.getTime()); log.debug("trying to change:" + reservation); try { reservation = em.merge(reservation); fail("failed to check version"); } catch (OptimisticLockException ex) { log.debug("caught expected exception:" + ex); }

35 Enterprise Java v121030Java EE Transactions35 Manual Transaction Control Java Transaction Service (JTS) –Java implementation of the OMG Object Transaction Service (OTS) –robust, complete, and complicated Java Transaction API (JTA) –simplified –javax.transaction –Java EE registers manual JTA interface in JNDI »java:comp/UserTransaction »also available from SessionContext.getUserTransaction(); –example »UserTransaction tx = //... »tx.begin(); »do something »tx.commit(); //or rollback –can be used by Session Beans »@Stateless »@TransactionManagement(TransactionManagerType.BEAN) »public class...

36 Enterprise Java v121030Java EE Transactions36 Bean Managed Transactions Stateless Session Beans –transactions must begin and end within the scope of a single method Stateful Session Beans –transaction may begin and end in separate methods

37 Enterprise Java v121030Java EE Transactions37 Exceptions and Transactions Default –Checked Exceptions do not impact transactions –System Exceptions automatically rollback transaction sub-classes of RuntimeException –EJBException –NullPointerException –RemoteException Customization –Checked exceptions can be configured to rollback transaction java.sql.SQLException true

38 Enterprise Java v121030Java EE Transactions38 Summary –ACID Transactions Automic, Consistent, Isolated, Durable –Transaction Scope Mandatory, Required, RequiresNew, Supports, NotSupported, Never –Class Annotations and XML Descriptors Is the Java code that independent of the transaction configuration? Are there portability issues from environment to environment –SessionSynchronization

39 Enterprise Java v121030Java EE Transactions39 Summary (cont.) Isolation Issues –dirty reads –repeatable reads –phantom reads Database Locks –Read Locks –Write Locks –Exclusive Write Locks Isolation Levels –Read Uncommitted –Read Committed –Repeatable Read –Serializable

40 Enterprise Java v121030Java EE Transactions40 Summary (cont.) Locking –Programmatic –Optimistic Bean Managed Transactions –JTA UserTransaction Exceptions and Transactions

41 Enterprise Java v121030Java EE Transactions41 References “Enterprise JavaBeans 3.0, 5 th Edition”; Burke & Monsen-Haefel; ISBN 0-596-00978-X; O'Reilly


Download ppt "Enterprise Java v121030Java EE Transactions1. Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be."

Similar presentations


Ads by Google