XA transaction processing

Source: Internet
Author: User

Xa interface detailed

The X/open XA interface is a two-way system interface that forms a communication bridge between the transaction manager (Transaction Manager) and one or more resource managers (Resource Manager). The transaction manager controls JTA transactions, manages the transaction life cycle, and coordinates resources. In JTA, the transaction manager is abstracted as an Javax.transaction.TransactionManager interface and implemented through the underlying transaction service (that is, JTS). The resource manager is responsible for controlling and managing actual resources, such as databases or JMS queues. Describes the relationship between the transaction manager, the resource manager, and the client application in a typical JTA environment:

Note that the medium XA interface forms the communication bridge between the transaction manager and the resource manager. Because of the bidirectional nature of the XA interface, XA supports the two-phase commit protocol, which we will discuss later in this chapter.

The content described in this chapter is difficult to cover all the details of the XA interface. If the reader cares about XA details, refer to the X/open XA interface specification (available in PDF format in http://www.opengroup.org/onlinepubs/009680699/toc.pdf).

When should I use XA?

In Java transaction management, a frequently confusing question is when to use XA and when not to use XA. Because most commercial application servers perform single-phase commit (One-phase commit) operations, performance degradation is not an issue worth considering. However, the non-necessity of introducing XA database drivers into your application can lead to unpredictable consequences and errors, especially when using the local transaction model (Transaction models). Therefore, it is generally necessary to avoid using XA when you do not need it. The following best practices describe when XA should be used:

Best practices

It is necessary to use the X/open XA interface only if you need to reconcile multiple resources (that is, databases, and message topics or queues) in the same transactional context.

An important point of view is that although your application may use multiple resources, XA is necessary only if the resources must be reconciled within the same transaction. Multiple resource scenarios include accessing two or more databases (not just multiple tables, but multiple databases that are separate from each other), or a database with one message queue or multiple message queues. You may have an app that uses both a database and a message queue. However, if these resources are not used in the same transaction, there is no need to use XA. The code that starts with this chapter, presets a fixed-income transaction, and then sends a message to the queue, which is an example of the need to use XA to maintain the acid characteristics.

The most common scenario for requiring and using XA is to reconcile database changes and message queues (or topics) in the same transaction. Note that these two operations may occur in completely different places (especially when using an ORM framework like hibernate). An XA transaction must reconcile two types of resources when a rollback event occurs, or leave the changes isolated from other transactions. If there is no XA, messages sent to the queue or subject will even arrive and be read before the transaction terminates. In an XA environment, messages in the queue are not freed until the transaction commits. In addition, if you are coordinating an operational database and a read-only database (that is, the reference database), you do not need XA. However, because XA supports read-only optimization, you may not see any performance penalty when a read-only data source is introduced into the XA transaction.

When you intend to use XA in your enterprise Java applications, there are a few hidden issues that need to be considered. These issues include two-phase commit (2pc,two-phase commit process), experience anomalies, and the use of XA drivers. The following chapters describe these issues separately.

Two-phase commit

The two-phase commit protocol (the two-phase commit protocol,2pc) is a mechanism that XA uses to coordinate multiple resources in a global transaction. The two-phase protocol adheres to the OSI (open System Interconnection, interconnect)/DTP standard, although it appears several years earlier than the standard itself. The two-phase commit agreement consists of two phases: the first phase (also known as the preparation phase) and the second phase (also called the commit phase). A good analogy to describe a two-stage submission is a typical wedding ceremony in which each participant (the groom and the bride in the wedding ceremony) must obey the arrangement and say "I do" before formally entering the marriage life. Consider the cup situation, one of the "participants" in the last moment before making a commitment to regret. The results of the two-stage submissions were also established, though not so destructive.

When a commit () request is issued from the client to the transaction manager, the transaction manager begins the two-phase commit process. In the first phase, all the resources are polled and asked if they are ready to submit the job. Each participant may answer "ready", "read-only (READ_ONLY)", or "not Ready (Not_ready)". If any of the participants responds with "Not Ready (Not_ready)" In the first stage, the entire transaction is rolled back. If all participants answer "ready", then these resources are submitted in the second phase. The answer to "read-only (READ_ONLY)" Resources is excluded from the second-phase processing of the protocol.

Two-phase commit becomes possible due to the ability of bidirectional communication in an XA environment. In a non-XA transactional environment, communication is only one-way, and two-phase commits cannot be done because the transaction manager is unable to receive a response from the resource manager. Most transaction managers, in order to optimize performance, release resources as quickly as possible, using multithreading to handle the first phase of polling and the second phase of the commit process. Shows the basic process for two-phase commits:

Shows the two-phase commit process when one of the resource managers (DBMS) has an error in the first stage of polling.

In this example, a commit request is sent to the transaction manager by a client that is running the global transaction (global transaction, a JTA transaction running under XA). In the first phase, the second resource manager returns a "not Ready (not_ready)" Response to the transaction manager. In this example, the transaction manager issues a rollback request to all participants and therefore coordinates all resources in the global transaction.

Some commercial application containers provide a feature called last-Participant support, which has an additional name called "last-Resource commit optimization". " Last participant support allows non-XA resources to participate in the global transaction. Under last contributor support, when a commit request for an XA environment reaches the transaction manager, the transaction manager first initiates the first phase of the XA resource process. Once the results from the XA contributor are returned consistently, the transaction manager initiates a request to commit (or roll back) the non-XA contributor. The result of this request determines how the remaining work of the two-phase commit process is performed. If a request to a non-XA resource succeeds, the transaction manager initiates a second phase and initiates a submission request to the XA participant. If a request to a non-XA participant is unsuccessful, the transaction manager initiates a second phase and requires all XA participants to roll back the transaction.

There are two issues with the "last participant support" mechanism. First, it is not portable between application containers. Second, because there is a long wait between the first-stage polling process and the non-XA last-commit resource submission, you will see an increase in the chance of experiencing an anomaly (heuristic Exception) when using this feature (which will be detailed in the next section). For these reasons, the "last participant support" feature should be avoided in general terms, unless forced to do so.

Most commercial application servers also support another optimization called "one-phase commit optimization (one-phase commit optimization)". If the transaction includes only one participant, the first stage processing is ignored and a single participant is notified of the submission. In this case, the consequences of the entire XA transaction depend on the results of a single participant.

Experience Anomaly (heuristic Exception) processing

In a two-phase commit process, the resource manager may use the policy of "empirical decision", either commit or roll back its own work without being controlled by the transaction manager. "Experiential decision" refers to the process of making intelligent decisions based on a variety of internal and external factors. When the resource manager does this, it will report an experience exception (heuristic Exception) to the client.

Fortunately, experience anomalies are not particularly common. It occurs only in the context of XA, in the process of two-phase commit, especially after the first phase of the transaction participant has responded. The most common cause of experience anomalies is the time-out between the first and second phases. When communication is delayed or lost, the resource manager may want to make a decision to commit or roll back its work to free up resources. It is not surprising that experience anomalies occur most frequently when the time period is high resource utilization. When you discover experience anomalies in your app, you should look for transaction timeouts, resource lockout issues, and resource overuse issues, which are often the root causes of experience anomalies. Occasional network delays or network failures can also lead to experience anomalies. Similarly, using the "Last Participant support" feature, as described in the previous section, can lead to more frequent occurrences of experience anomalies.

JTA exposed three kinds of JTA experience abnormalities of heuristicrollbackexception,heuristiccommitexception, as well as heuristicmixedexception. We use the following scenario to illustrate:

Scenario 1 : In Commit Heuristicrollbackexception of the operation phase Exception

In this scenario, the client performs the update operation in an XA environment, initiating a request to the transaction manager to commit the current transaction. The transaction manager opens the first phase of the two-phase commit process and polls the resource manager. All resource managers report to the transaction manager that they are ready to commit the transaction. However, between the first and second phases of the (two-phase submission process) each resource manager independently made an empirical decision to roll back the work that they had done. When the second stage is entered, the commit request is sent to the resource manager, because the work has been rolled back before, and the transaction manager will report the heuristicrollbackexception exception to the caller.

When such exceptions are accepted, the usual way to handle this is to pass this exception back to the client and have the client resubmit the request. We cannot simply call the commit request again, because the update that was generated for the database has been removed from the database transaction log with the rollback operation. The following sequence diagram illustrates this scenario:

First step: First stage processing (preparation phase)

Step two: Between the first and second phases

Step three: Second stage processing (Submission phase)

As you can see from the sequence diagram, two resource managers roll back their own work, although they report the ready response to the transaction manager in the first phase. Don't worry about what happens to these anomalies, we'll discuss them in further chapters.

Scenario 2 : In Commit Heuristicmixedexception of the operation phase Exception

In this scenario, the client performs the update operation in an XA environment, initiating a request to the transaction manager to commit the current transaction. The transaction manager opens the first phase of the two-phase commit process and polls the resource manager. All resource managers report to the transaction manager that they are ready to commit the transaction. Unlike the first scenario, where the gap between the first and second phases occurs, a resource manager (such as Message Queuing) makes an empirical decision to submit its work, while other resource managers, such as databases, make empirical decisions about rollback. In this case, the transaction manager reports the heuristicmixedexception exception to the caller.

In this case, it is very difficult to choose the correct follow-up, because we do not know which resources are submitting the work and which resources are rolling back the work. All target resources are therefore in a state of inconsistency. Because the resource managers are independent of each other's interventions, there is no coordination or communication between them as far as empirical decisions are concerned. Solving this anomaly usually requires a human intervention. The following sequence diagram illustrates this scenario:

First step: First stage processing (preparation phase)

Step two: Between the first and second phases

Step three: Second stage processing (Submission phase)

Note In the illustration above, one resource manager submits its work, while the other resource manager chooses to roll back its work. In this case, the transaction manager will report heuristicmixedexception.

Use XA for Message Queuing or topics

The resources used under the XA interface must implement the Javax.transaction.xa.XAResource interface so that they can join the XA global transaction. For JMS destinations (queues or topics), this can be done by configuring them in a specific application Server console or hypervisor. The part that really activates XA is the JMS connection factory (Connection Factory). Once the JMS connection factory supports XA, messages sent to the JMS queue or topic are not freed until the two-phase commit process ends. In the absence of XA, messages sent to the JMS destination are immediately freed and can be picked up by the recipient, regardless of the outcome of the transaction context in which they are located.

In the WebLogic application server, you can services| in the management console jms| Connection The JMS connection factory that activates XA in the factories configuration. On transactions This page, there is an option called Xa Connection Factory enabled, which allows the JMS target to be included in the JTA global transaction. For IBM WebSphere, you can resources| in the management console WebSphere JMS providers| Under Connection factories path, select the JMS connection Factory feature that uses XA. A checkbox named Enablexa activates the XA JMS connection factory.

Using XA for a database

You can enable XA for your database by using the XA version of the database driver. Since the XA version of the database driver is usually much more difficult than non-XA, a piece of advice is not to use the XA driver when it is unavoidable.

Using an XA version of the database driver often results in unpredictable and difficult-to-resolve errors. For example, replacing a non-XA drive with an XA driver often produces errors that are difficult to track. Therefore, the XA driver should be introduced early in the project development and testing phase (to expose the problem early and resolve it).

When using an XA version of a database driver, the types of errors you may encounter include local transaction errors and nested transaction errors. These errors occur when you attempt to open a new transaction while an XA global transaction is in progress. This situation occurs in multiple environments, but the most common scenario is the combination of the local transaction model with the declarative transaction model and the use of stored procedures in an XA environment.

When using stored procedures in an XA environment, invoking DDL (data definition statements, such as Create Table,begin tran,end TRAN) in a stored procedure often results in an error. This is the most frequent cause of XA errors and is difficult to fix. For example, in Oracle, when using XA, you may see the following error message:

Ora-02089:commit isn't allowed in a subordinate session

If you use a non-XA database driver, you probably won't see this error because the JTA transaction is paused when the DDL statement executes. When you see this error message, it indicates that your stored procedure contains DDL code and that the local transaction (managed by the resource manager) tries to submit its work.

It is often difficult to remove existing DDL statements from stored procedures, because they must have a reason for existence there, or perhaps these stored procedures are shared by other applications (which are too large to remove). One effective way to circumvent the problem is to manually suspend the transaction before invoking these stored procedures, and continue the transaction after the stored procedure returns. Using this technique avoids XA-related local and nested errors. However, if you do this, the changes made by the stored procedure are independent of the JTA global transaction commits and therefore violate the acid characteristics of the transaction. So it's just about bypassing the problem, not solving it. The following code snippet shows the details of this technique:

... InitialContext CTX = new InitialContext (); TransactionManager TM = (Javax.transaction.TransactionManager) ctx.lookup ("Javax.transaction.TransactionManager"); Transaction CURRENTTX = null; try {     currenttx = Tm.suspend ();     INVOKESPWITHDDL (); } finally {     if (currenttx! = null)    

Even in the context of declarative transactions, we can still use TransactionManager to suspend and resume transactions in code mode. This technique avoids the SQL exception information in an XA environment, but it doesn't really solve the problem. --The only way to really solve the problem is to delete those offending DDL statements in the stored procedure or to use a JTA transaction service that supports nested transactions.

Summarize

The most important idea to express in this chapter is to understand when you really need to use the XA version of the database driver. Many developers and architects always insist on using the XA version of the database driver, although there is no reasonable reason to use them. If you need to reconcile multiple changes in a resource (database, message queue, subject, or JCA) in the same transaction, there is no doubt that you need to introduce an XA interface. Otherwise, you must avoid XA.

Another suggestion for using XA is that when you encounter a problem, don't always guess that you're using an XA database driver that might be riddled with errors. The problem is most likely caused by your application code or transaction logic, not the XA driver.

XA transaction processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.