Topics. Advanced Java Programming. Transaction Definition. Background. Transaction basics. Transaction properties

Similar documents
Plan. Department of Informatics. Advanced Software Engineering Prof. J. Pasquier-Rocha Cours de Master en Informatique - SH 2003/04

Business-Driven Software Engineering (6.Vorlesung) Bean Interaction, Configuration, Transactions, Security Thomas Gschwind <thg at zurich.ibm.

JSpring and J2EE. Gie Indesteege Instructor & Consultant

Enterprise Java Beans

Using the Transaction Service

Java EE Architecture, Part Two. Java EE architecture, part two 1

Component-Based Software Engineering. ECE493-Topic 5 Winter Lecture 26 Java Enterprise (Part D)

Outline. Chapter 5 Application Server Middleware. Types of application server middleware. TP monitors CORBA Server-side components and EJB Summary

SQL: Transactions. Introduction to Databases CompSci 316 Fall 2017

Outline. Chapter 5 Application Server Middleware WS 2010/11 1. Types of application server middleware

CSE 530A ACID. Washington University Fall 2013

DATABASE TRANSACTIONS. CS121: Relational Databases Fall 2017 Lecture 25

Outline. Chapter 5 Application Server Middleware. Types of application server middleware. TP monitors CORBA Server-side components and EJB Summary

SQL: Transactions. Announcements (October 2) Transactions. CPS 116 Introduction to Database Systems. Project milestone #1 due in 1½ weeks

What are Transactions? Transaction Management: Introduction (Chap. 16) Major Example: the web app. Concurrent Execution. Web app in execution (CS636)

Transaction Management: Introduction (Chap. 16)

Transaction Management

CHAPTER 4 TRANSACTIONS

Transactions and Isolation

IBM. Enterprise Application Development with IBM Web Sphere Studio, V5.0

Databases - Transactions

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 10: Transaction processing. November 14, Lecturer: Rasmus Pagh

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

Java Enterprise Edition

transactional processing

Introduction to Data Management CSE 344

L i (A) = transaction T i acquires lock for element A. U i (A) = transaction T i releases lock for element A

Transaction Management Chapter 11. Class 9: Transaction Management 1

CHAPTER 3 RECOVERY & CONCURRENCY ADVANCED DATABASE SYSTEMS. Assist. Prof. Dr. Volkan TUNALI

Database Systems CSE 414

Databases - Transactions II. (GF Royle, N Spadaccini ) Databases - Transactions II 1 / 22

Transactions and Transaction Managers

CORBA Object Transaction Service

Transactions. ACID Properties of Transactions. Atomicity - all or nothing property - Fully performed or not at all

Locking, concurrency, and isolation

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER

Part VII Data Protection

Database Systems CSE 414

ITdumpsFree. Get free valid exam dumps and pass your exam test with confidence

Seminar 3. Transactions. Concurrency Management in MS SQL Server

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

Developing JTA Applications for Oracle WebLogic Server 12c (12.2.1)

JDBC, Transactions. Niklas Fors JDBC 1 / 38

CSE 344 MARCH 9 TH TRANSACTIONS

Announcements. SQL: Part IV. Transactions. Summary of SQL features covered so far. Fine prints. SQL transactions. Reading assignments for this week

CSE 344 MARCH 25 TH ISOLATION

Transactions. Introduction

Distributed Transactions and PegaRULES Process Commander. PegaRULES Process Commander Versions 5.1 and 5.2

BEAAquaLogic. Service Bus. Interoperability With EJB Transport

5. Distributed Transactions. Distributed Systems Prof. Dr. Alexander Schill

Enterprise JavaBeans 3.1

Introduction to Data Management CSE 344

Enterprise JavaBeans, Version 3 (EJB3) Programming

UNIT-III EJB APPLICATIONS

Transactions. Kathleen Durant PhD Northeastern University CS3200 Lesson 9

Transaction Management: Concurrency Control, part 2

Locking for B+ Trees. Transaction Management: Concurrency Control, part 2. Locking for B+ Trees (contd.) Locking vs. Latching

Introduction to Data Management CSE 414

JAP transaction processing failure scenarios

1Z Oracle. Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade

Fast Track to EJB 3.0 and the JPA Using JBoss

Transactions & Concurrency Control

Courses For Event Java Advanced Summer Training 2018

Oracle Tuxedo. CORBA Technical Articles 11g Release 1 ( ) March 2010

ITcertKing. The latest IT certification exam materials. IT Certification Guaranteed, The Easy Way!

SCBCD EXAM STUDY KIT. Paul Sanghera CX JAVA BUSINESS COMPONENT DEVELOPER CERTIFICATION FOR EJB MANNING. Covers all you need to pass

Database Systemer, Forår 2006 IT Universitet i København. Lecture 10: Transaction processing. 6 april, Forelæser: Esben Rune Hansen

Oracle Fusion Middleware

Distributed Data Management Transactions

Module 15: Managing Transactions and Locks

Introduction to Data Management CSE 344

Weak Levels of Consistency

Enterprise JavaBeans. Layer:01. Overview

Chapter 22. Transaction Management

Developing Applications with Java EE 6 on WebLogic Server 12c

COSC344 Database Theory and Applications. Lecture 21 Transactions

Conception of Information Systems Lecture 8: J2EE and EJBs

Enterprise JavaBeans. Layer:03. Session

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

SUN Sun Cert Bus Component Developer Java EE Platform 5, Upgrade. Download Full Version :

Enterprise JavaBeans (I) K.P. Chow University of Hong Kong

presentation DAD Distributed Applications Development Cristian Toma

Data Management in Application Servers. Dean Jacobs BEA Systems

Chapter 6 Enterprise Java Beans

Exam Questions 1Z0-895

Java SE7 Fundamentals

Overview. Introduction to Transaction Management ACID. Transactions

Java EE 7: Back-End Server Application Development

A transaction is a sequence of one or more processing steps. It refers to database objects such as tables, views, joins and so forth.

Distributed Applications (RMI/JDBC) Copyright UTS Faculty of Information Technology 2002 EJB EJB-3

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved.

Database Usage (and Construction)

Chapter 13. Concurrency Control. In This Chapter. c Concurrency Models c Transactions c Locking c Isolation Levels c Row Versioning

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Sharpen your pencil. entity bean synchronization

Migration Technical Resources. Angelo Santagata EMEA Partner Technical Services Oracle Server Technologies

Advances in Data Management Transaction Management A.Poulovassilis


133 July 23, :01 pm

Middleware and Distributed Systems. Transactions. Martin v. Löwis

Transcription:

Advanced Java Programming Transactions v3 Based on notes by Wayne Brooks & Monson-Haefel, R Enterprise Java Beans 3 rd ed. Topics Transactions background Definition, basics, properties, models Java and transactions JTA,JTS EJB support Transaction scope, attributes Isolation, locking Transactions and enterprise Java applications Web transactions - Declarative, programmatic EJB transactions Declarative, programmatic Copyright UTS Transactions Transactions-1 Copyright UTS Transactions Transactions-2 Background Transactions "traditionally" for databases Many applications have transactional requirements Eg: the following 2 must complete as 1 transaction deposit(acct1, 1000) withdraw(acct2, -1000) Transaction Definition A transaction is a unit of work Accesses one or more shared resources A set of one or more related activities Activities must be completed together or not at all Cohesion of unit is normally mission critical Eg: Bank withdraw from one source, deposit to another Order System locate item, charge account, schedule shipment Copyright UTS Transactions Transactions-3 Copyright UTS Transactions Transactions-4 Transaction basics Usually have three main operations: begin transaction commit transaction abort transaction Transaction properties All transactions have the following properties (usually called ACID properties) Atomicity "all or nothing" happens Consistency Different objects accessing data see a consistent view System is always in a "consistent" state Isolation Cannot view intermediate results of other transactions Durability Ensure that committed data remains committed, and uncommitted data is rolled back, in the event of failure Copyright UTS Transactions Transactions-5 Copyright UTS Transactions Transactions-6

ACID properties Transaction manager responsible for ensuring ACID properties are maintained Transaction manager might be: DBMS eg: Oracle TP monitor eg: IBM CICS, Bea Tuxedo Java application server your applications don't have to deal with all the possible things that could go wrong during a transaction you leave it to the container / transaction manager Transaction Models Different transaction managers support mainly 2 transaction models Flat Nested J2EE application servers only have to support the "flat" transaction model Copyright UTS Transactions Transactions-7 Copyright UTS Transactions Transactions-8 Flat Transaction Model Nested Transaction Model From Monson-Haefel, R Enterprise Java Beans 3 rd ed. Copyright UTS Transactions Transactions-9 From Monson-Haefel, R Enterprise Java Beans 3 rd ed. Copyright UTS Transactions Transactions-10 Transaction Management Transaction manager ensures ACID properties are maintained even over a network X/Open has a distributed transaction processing standard (based on two phase commit) Two phase commit (2PC) Phase 1: Prepare to commit Phase 2: Actual commit Topics Transactions background Definition, basics, properties, models Java and transactions JTA,JTS EJB support Transaction scope, attributes Isolation, locking Transactions and enterprise Java applications Web transactions - Declarative, programmatic EJB transactions Declarative, programmatic Copyright UTS Transactions Transactions-11 Copyright UTS Transactions Transactions-12

Java & Transactions Two key acronyms: JTA Java Transaction API JTS Java Transaction Service JTA JTA is one of the simplest Java APIs from a user (application developer) perspective javax.transaction.usertransaction: JTA is the API your code uses, if you want to deal with transactions programmatically JTS is the vendor implementation of transaction management in Java JTS is a Java mapping of CORBA's Object Transaction Service (OTS) sometimes you see references to JTS/OTS this is why void begin() void commit() void rollback() void setrollbackonly() int getstatus() void settransactiontimeout(int seconds) Copyright UTS Transactions Transactions-13 Copyright UTS Transactions Transactions-14 Applications & Transactions Not all parts of an application require transactions Transactions are designed to enforce system integrity however, they also introduce overhead parts of the application that do not require transaction support may be declared/coded as such, to reduce overhead For now, let's consider transactions on a methodby-method basis EJB Transaction Support J2EE allows us to manage transactions at the container or programmer level. 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 Copyright UTS Transactions Transactions-15 Copyright UTS Transactions Transactions-16 Transaction Scope A Unit of Work consists of one or more tasks Tasks == EJB methods Ends when: thread of execution completes normally an exception is thrown transaction is rolled back The scope of each EJB method depends on the bean s declared transaction attributes Copyright UTS Transactions Transactions-17 Transaction Attributes Required uses existing transaction, or creates a new one RequiresNew suspends any old transaction and creates a new one NotSupported suspends any old transaction and runs with no trans. Supports (default with J2EE) may run with transaction depends on caller Never refuses to run within a transaction Mandatory refuses to run without a transaction Copyright UTS Transactions Transactions-18

EJB3 annotation Can do this at CLASS level: @TransactionAttribute(MANDATORY) public class MyBean implements My { public void setpay(int staffid, float salary) { Or at METHOD level: public class MyBean implements My { @TransactionAttribute(MANDATORY) public void setpay(int staffid, float salary) { Note: default transaction is SUPPORTS for class. Setting the Declarative Transaction Attribute <ejb-jar> <assembly-descriptor> <container-transaction> <ejb-name>account</ejb-name> <method-name> * </method-name> </method> <trans-attribute> Required </trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> Copyright UTS Transactions Transactions-19 Copyright UTS Transactions Transactions-20 Required RequiresNew EJB s Transaction Context Joins the transaction scope if invoked as part of a transaction Initiates its own transaction context Copyright UTS Transactions Transactions-21 EJB s Transaction Context Initiates its own transaction scope regardless of being called within existing transaction Initiated transaction completes prior to returning to caller Copyright UTS Transactions Transactions-22 Not Supported Supports Transaction is suspended during the method of the Invoked EJB; resumes when method complete Transaction scope is not propagated to or anything it invokes Copyright UTS Transactions Transactions-23 Joins the transaction scope if invoked as part of a transaction Can be invoked outside of a transaction Copyright UTS Transactions Transactions-24

Never Mandatory Transaction Exception Transaction Exception Throws a Transaction Exception if called within a transaction context Must be invoked outside of a transaction context Copyright UTS Transactions Transactions-25 Joins the transaction scope if invoked as part of a transaction Throws a Transaction Exception if not called within a transaction context Copyright UTS Transactions Transactions-26 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 Database Locks How do you prevent overlapping transactions from viewing/updating the shared data? Typical situations: 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 Typically managed by the DBMS Copyright UTS Transactions Transactions-27 Copyright UTS Transactions Transactions-28 Transaction Isolation Levels Solution: specify locking mechanism at the transaction level ie: 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 Specifying Isolation Level <weblogic-ejb-jar> <transaction-isolation> <isolation-level> TRANSACTION_READ_COMMITTED </isolation-level> <ejb-name>account</ejb-name> <method-name>*</method-name> </transaction-isolation> Copyright UTS Transactions Transactions-29 Copyright UTS Transactions Transactions-30

Isolation Levels 1 Never transactions are not supported Read Uncommitted other objects can read uncommitted results dangerous! Example T1 begins and updates a row T2 reads the updated row T1 rolls back T2 has read uncommitted, dirty data ( dirty read) Isolation Levels 2 Read Committed prevents dirty reads but does not guarantee repeatable reads what is a repeatable read? should return the same value if read twice in a same transaction Example T1 begins and reads a row T2 updates the row and commits T1 reads the row again Non-Repeatable Read as T1 sees different value to its first read Copyright UTS Transactions Transactions-31 Copyright UTS Transactions Transactions-32 Isolation Levels 3 Repeatable Read prevents dirty and nonrepeatable reads however, phantom reads are still possible a phatom reads ocurrs if a row has been added or deleted and the transaction sees the side effect Isolation Levels 4 Serializable prevents dirty, nonrepeatable and phantom reads highest level, guarantees serialisability of transactions lowest performance Example T1 reads using a WHERE clause T2 inserts a row and commits T1 reads using the same WHERE clause A phantom read occurs if the second read contains the inserted row data expensive to implement and does not provide true serializable transactions Copyright UTS Transactions Transactions-33 Copyright UTS Transactions Transactions-34 Programmatic settings Isolation Level can be set programmatically: Connection.setTransactionIsolation() set for a given connection (only for BMP) Constants are defined in Connection class conn.settransactionisolation (Connection.TRANSACTION_READ_COMMITTED); Typical settings Transaction Attribute: Required Ensures that an operation runs inside a transaction "just in case" it does something that should be protected by a transaction Isolation Level: Read Committed Lowest "safe" level Setting higher levels offers more reliability, but reduced concurrency, reduced performance Enables readers to proceed without waiting for an update to commit in a web application most users are browsing the data Copyright UTS Transactions Transactions-35 Copyright UTS Transactions Transactions-36

Topics Transactions background Definition, basics, properties, models Java and transactions JTA,JTS EJB support Transaction scope, attributes Isolation, locking Transactions and enterprise Java applications Web transactions - Declarative, programmatic EJB transactions Declarative, programmatic Enterprise Java Transactions You may wish to use transactions: in a servlet/jsp container (web server) in an EJB container (application server) You may wish to use transactions: declaratively (preferred) programmatically (when you must) The following pages go through these combinations Copyright UTS Transactions Transactions-37 Copyright UTS Transactions Transactions-38 Declarative web transactions Not possible!!! For web components (servlets/jsps), if you want to use transactions, you must do it programmatically! J2EE goal: manage transactions by the EJB container. your servlets/jsps should only have presentation logic they should only be formatting the data, not carrying out any business logic, therefore should not need transactions! Copyright UTS Transactions Transactions-39 Programmatic web transactions import javax.transaction.*; import javax.naming.*; public void doget() { try { Context ctx = new InitialContext(); UserTransaction ut = (UserTransaction) ctx.lookup("weblogic.transaction.usertransaction"); ut.begin(); // do some transactional ops here, e.g. access DBMS ut.commit(); catch (Exception e) { Copyright UTS Transactions Transactions-40 Programmatic web transact (2) Some restrictions: transactions cannot span multiple web requests if using multi-threaded servlet, the transaction must be started and completed only from the "main" thread You might use transactions in a servlet/jsp if: you were building a small-scale application with no EJBs, and had the servlets/jsps directly accessing multiple databases In EJB3 @TransactionManagement(BEAN) @Stateless public class PayrollBean implements Payroll { @Resource UserTransaction utx; @PersistenceContext EntityManager payrollmgr; public void setpay(int empid, float salary) { utx.begin(); payrollmgr.find(employee.class, empid).setsalary(salary); utx.commit(); Copyright UTS Transactions Transactions-41 Copyright UTS Transactions Transactions-42

Declarative EJB transactions <assembly-descriptor> <container-transaction> <ejb-name>mysessionejb</ejb-name> <method-intf>remote</method-intf> <method-name>writelogfile</method-name> </method> <trans-attribute>requiresnew</trans-attribute> </container-transaction> <container-transaction> <ejb-name>mysessionejb</ejb-name> <method-intf>remote</method-intf> <method-name> * </method-name> </method> <trans-attribute>required</trans-attribute> </container-transaction> </assembly-descriptor> Copyright UTS Transactions Transactions-43 Declarative EJB transactions (2) You specify bean transactions on a method-bymethod basis Entity beans can only use container-managed transactions you have no choice about it Session beans can choose between container-managed transactions (declarative) and bean-managed transactions (programmatic) as usual, container-managed transactions are preferred Copyright UTS Transactions Transactions-44 Declarative EJB transactions (3) Even using declarative transactions, you might want to notify the transaction manager that the transaction must rollback methods are provided on the EJB SessionContext: void setrollbackonly() boolean getrollbackonly() EJB 3 transactions In EJB 3 session beans: declare transaction using @TransactionAttribute(TransactionAttributeType) (where transactionattributetype is SUPPORTS, REQUIRED etc) Recall that every EJB has access to it's SessionContext through your implementation of: void setsessioncontext(sessioncontext sc) Copyright UTS Transactions Transactions-45 Copyright UTS Transactions Transactions-46 Programmatic EJB transactions public class MySessionEJB implements SessionBean { SessionContext ejbctx; public void mybusinesslogicmethod() { UserTransaction ut = ejbctx.getusertransaction(); ut.begin(); // perform transactional operations here ut.commit(); Programmatic EJB transact (2) Should be avoided Container managed transactions are easier to use, and allow different objects to be more easily composed into larger transactions Only useful for fine-grain transactional behaviour where you don't want an entire method to be part of a transaction, but just a few lines of code Uses pure JTA easy! Copyright UTS Transactions Transactions-47 Copyright UTS Transactions Transactions-48

Container transaction support The container automatically propagates transaction contexts So if you create a transaction in a servlet, and from the servlet you call an EJB with the "Requires" attribute, the EJB will execute under the boundary of the servlet's transaction If one EJB (e.g. session) makes calls on another EJB (e.g. entity), the transaction context is propagated Summary Transactions are an important part of enterprise applications fortunately EJB containers make it easy Container-managed (declarative) transactions are preferred to bean-managed (programmatic) choose the right transaction attribute for each method if you are unsure, "Required" is a safe bet Remember that all transaction management has performance implications. Locking can bring throughput to a halt. Copyright UTS Transactions Transactions-49 Copyright UTS Transactions Transactions-50