1 / 25

Advanced Transaction Management Concepts

Advanced Transaction Management Concepts. More Detail on Spring’s Transaction Management Support. Topics in this session. Transaction Collaborations Transaction Attributes (propagation etc.) Transaction Design Patterns. Transaction Attributes. Propagation Isolation Timeout

turner
Download Presentation

Advanced Transaction Management Concepts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Transaction ManagementConcepts More Detail on Spring’s Transaction Management Support

  2. Topics in this session • Transaction Collaborations • Transaction Attributes (propagation etc.) • Transaction Design Patterns

  3. Transaction Attributes • Propagation • Isolation • Timeout • Read/write access • Synchronization • Resource enlistment (XA) Useful resource: http://www.javaworld.com/jw-07-2000/jw-0714-transaction.html

  4. Transaction Propagation • Defines behaviour of “nested” transactions – when a new transaction is started inside an existing one. • Configured in TransactionDefinition. • TransactionTemplate is a TransactionDefinition. • TransactionProxyFactoryBean accepts propagation parameters and passes them down into the templates it creates. • Spring 2.0 with Java 5: see Propagation enumeration.

  5. Understanding transaction propagation A Transaction B Transaction 1 Transaction 2 Caller Transactional method 1 Transactional method 2 Is there an existing transaction? Should method 2 execute in that transaction (A) or should a new transaction be created (B), with outer transaction suspended? Transaction created, committed or rolled back as needed Behavior driven by metadata for the method Behavior is driven by metadata for the method

  6. The 6 + 1 Propagation Behaviours (1) Normally the default (platform dependent) • REQUIRED • Execute within a current transaction, create a new one if none exists • Scenario (A) from previous slide • SUPPORTS • Execute within a current transaction, execute non-transactionally if none exists • MANDATORY • Execute within a current transaction, throw an exception if none exists • REQUIRES NEW • Create a new transaction, suspending the current transaction if one exists • Not a true “nested” transaction • “Outer” transaction could ultimately roll back, but “inner” transaction would still commit • Analogous to an Oracle “autonomous transaction”, as with sequences • Scenario (B) from previous slide

  7. The 6 + 1 Propagation Behaviours (2) • NOT SUPPORTED • Execute non-transactionally, suspending the current transaction if one exists • NEVER • Execute non-transactionally, throw an exception if a transaction exists • NESTED • Use savepoints to begin a nested transaction, which can “commit” yet be rolled back if the outer transaction rolls back • Not supported by EJB CMT or JTA • Not an option if you have distributed transactions • Only an option if you are using a single resource, such as Oracle, that understands savepoints • Not presently supported by O/R mapping products such as Hibernate • This may change Spring only; Other 6 follow familiar EJB CMT semantics

  8. Transaction Isolation • Defines behaviour of non-nested transactions. • Configured in TransactionDefinition. • Principally concerned with visibility of data, e.g. uncommitted writes in Transaction A visible to Transaction B. • Platform-dependent – not all behaviours will be supported on all platforms (e.g. only really applies to database transactions). • Spring 2.0 with Java 5: see Isolation enumeration.

  9. Isolation Behaviours • DEFAULT • Use the default isolation level of the underlying datastore. • READ_UNCOMMITTED • Allows a row changed by one transaction to be read by another transaction before any changes in that row have been committed (a "dirty read"). • If any of the changes are rolled back, the second transaction will have retrieved an invalid row. • READ_COMMITTED • Only prohibits a transaction from reading a row with uncommitted changes in it • REPEATABLE • Also prohibits the situation where one transaction reads a row, a second transaction alters the row, and the first transaction rereads the row, getting different values the second time (a "non-repeatable read") • SERIALIZABLE • Further prohibits the situation where one transaction reads all rows that satisfy a WHERE condition, a second transaction inserts a row that satisfies that WHERE condition, and the first transaction rereads for the same condition, retrieving the additional "phantom" row in the second read Normally the default (platform dependent)

  10. Transaction Timeout • Configured (seconds) in TransactionDefinition. • Default is never (TIMEOUT_DEFAULT = -1). • In a distributed environment it can be useful to enable timeouts. But timeout events should be monitored in production because they normally signify a problem that needs to be addressed. • Timeout will normally lead to a rollback because framework throws an exception – usually UnexpectedRollbackException. • Platform-dependent (relies on underlying providers).

  11. Read-only Transactions • Configured (boolean) in TransactionDefinition. • Default is false. • Often added to declarative configuration as part of pointcut (e.g. get* gets readOnly=true, set* gets readOnly=false). • Platform-independent flag. • Actual behaviour is platform-dependent (relies on underlying providers).

  12. Transaction Synchronization • Callback for Spring transaction boundaries – similar concept but not the same as JTA Synchronization • Added to transaction through TransactionSynchronizationManager. • Also see flag on AbstractPlatformManager which prevents synchronizations from being added in some circumstances: • SYNCHRONIZATION_ALWAYS • SYNCHRONIZATION_NEVER • SYNCHRONIZATION_ON_ACTUAL_TRANSACTION = only when there is a separate actual back-end transaction (e.g. the inner transaction when propagation level is Propagation.SUPPORTS) • Used internally in transaction manager implementations. • Can also be used to manage resources, e.g. switch data sources dynamically for the duration of a transaction. Normally the default (platform dependent)

  13. Transaction Synchronization Example • The PlatformTransactionManager handles the callbacks, once registered. See docs for javax.transaction.Status TransactionSynchronizationManager .registerSynchronization( new TransactionSynchronizationAdapter() { public void afterCompletion(int status) { // do stuff, release resources etc... } }); This code will execute at the end of a transaction See TransactionSynchronization docs for other callback method definitions

  14. Transaction Synchronization and Propagation • If propagation level is Propagation.REQUIRED then inner transactions are not “actual” transactions. • In that case Synchronizations are associated with lifecycle of the outer transaction. • N.B. this is different than JTA Synchronizations – in JTA the inner transaction has its own lifecycle.

  15. Resource Enlistment (XA) • JTA includes standard API for XA (Distributed Transaction Processing). • When transactions must span multiple remote resources we are forced to use more complicated technology. • Spring still hides it behind the same abstractions. • But there is always a cost in maintenance as well as performance. • Often it is better to keep it simple until there is a clear need for XA transactions.

  16. Customizing Transaction Semantics • The <tx:attributes/> element specifies the metadata describing what methods of the target bean to intercept transactionally and with what semantics. • Transaction semantics may be customized, but default to: • RuntimeExceptions roll-back, normal (checked) Exceptions don’t • Transactions are read/write • propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRED • isolation level = TransactionDefinition.ISOLATION_DEFAULT • timeout = TransactionDefinition.TIMEOUT_DEFAULT

  17. Declarative Transaction Attributes • The <tx:attributes> element is used to specify the attributes of the transaction definition. • Contains a sequence of <tx:method> elements, each of which can have • name: method name pattern with wildcards (not regexp) • propagation: see Propagation enum • isolation: see Isolation enum • timeout: seconds • read-only: boolean • rollback-for: comma-separated list of exception classes (package names optional) • no-rollback-for: comma-separated list of exception classes

  18. Properties of the ‘Transactional’ Annotation • propagation (enum: Propagation) • isolation (enum: Isolation) • readOnly (boolean) • rollbackFor (array of classes) • rollbackForClassname (array of strings) • noRollbackFor (array of classes) • noRollbackForClassname (array of strings)

  19. Transaction Design Patterns • Motivations • Retain atomicity, consistency, isolation, and durability (ACID) • Prevent tier-leakage • Keep business logic and transaction management separate • Minimise resource usage and potential performance issues • Solutions • Transaction Template • Transaction Delegate • Service Layer Transaction • Open Transaction In View • Two-phase Commit (2PC)

  20. Transaction Template Pattern • Familiar to all Spring users • Wrap a group of service calls in a single transaction • Pros: • Simple to use • Explicitly maintains ACID properties • Cons: • Invasive: too many participants • Scattering: hard to keep track of boundaries

  21. Transaction Delegate Pattern • Delegate transactional logic to a completely separate service • Command pattern version and AOP version. • Spring users tend to favour the AOP – the delegate is the Transaction Proxy. • Pros: • Separates concerns: transactions and business logic. • Minimum number of participants: only the delegate needs to know about transactions. • Easy to re-configure transaction boundaries. • Cons: • Can be hard to debug and diagnose problems.

  22. Service Layer Transaction • Business logic is implemented in Service Layer. • The high-level units of work (use cases) are carried out here, through multiple calls to a Data Access Layer. • Transactions are demarcated in the Service Layer. • Pros: • Transaction boundaries tied to business logic. • Retain ACID properties across user-oriented operations. • Cons: • Sometimes the business logic is emergent: it is only known at run time.

  23. Open Transaction In View • Companion to Open Session In View (OSIV) – see e.g. Hibernate documentation, or MVC Webflow book. • In a web application wrap the whole request cycle in a single transaction. • Variants: be a bit smarter about which requests need transactions and/or read-only=false attributes. • Pros: • Simple to apply and simple to follow transaction logic and boundaries • Works well in simple applications with one database and no other remote resources. • Cons: • Can block resources for unacceptably long periods if requests are “busy”. • Expensive if many requests don’t actually need a transaction.

  24. Two-Phase Commit (2PC) • Distributed algorithm. • Not the only such algorithm, but the most commonly found owing to XA standard . • Two phases: commit-request; commit. • Collaborators: co-ordinator and cohorts. Co-ordinator is responsible for notifying cohorts of the overall transaction status. • Pros: • Allows transactions to span multiple remote resources. • Mostly transparent to clients. • Cons: • Blocking protocol: performance penalty. • Biased to the abort case rather than the complete case. • Can be difficult to maintain and operate, also debug.

  25. Topics in this session • Transaction Collaborations • Transaction Attributes (propagation etc.) • Transaction Design Patterns

More Related