Two phase commit in action

Since programming JEE applications I always wanted to see a two phase commit working. That is that all the changes made to transactional resources are really rolled back when an exception occurs.

I selected tomee and maven as the platform for implementing a test for two phase commits. The complete example can be found here. It is based on this example from the tomee examples.

The example contains a simple stateless EJB that contains the test method:

In this method two other stateless session beans are used to write a movie object to two different databases respectively. The methods that insert the movie into the database contain a boolean parameter that indicates whether a runtime excpetion should be thrown from that method or it the method should terminate normally. The first invocation is not to throw an exception, the second one should. And it is expected that the method should not terminate normally as indicated by the fail-statement.

The unit test for this ejb looks like this:

First an instance of the test ejb is looked up and subsequent the method described above is called. An EJBException is expected to be thrown. The last lines contain the assertions for checking that the insert to the first database actually have been rolled back.

In order to run the example simply type:

This example is of course very basic. But it never the less validates the powerful mechanism behind the jee transaction model.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">