Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Transactions and Beans:Why have a dog and bark yourself?

Transactions and Beans:Why have a dog and bark yourself?

That was what an old girlfriend periodically said to me. Needless to say, we're no longer together - I wasn't keen on the comparison. "Shall I compare thee to a dog?" is rather less poetic than I like. But in thinking about this month's transaction column, the comment seemed strangely germane to the world of app servers and transactions.

I've mentioned several times in these articles that the underlying purpose of an application server is to provide out-of-the-box functionality that you would otherwise have to write and maintain yourself, despite it having only indirect relevance to the business problem at hand. For example, "Transfer money from my current account to my savings account" is an operation that any banker would comprehend. "Implement a two-phase commit transaction manager" would probably leave them dazed and confused, despite the implicit requirement for an atomic transfer of funds.

Bankers never seem keen on creating money (unless it's created in their pockets) or making it vanish (unless it vanishes from your pocket and reappears in theirs). With this in mind, the wise developer buys an app server and uses its JTA transaction manager to provide the necessary atomicity guarantees underlying the business operation, while the unwise (and shortly to be unemployed) one goes off on a two-year mission to implement transaction services, because it's fun to do.

I'll Be Your Dog
So, it's clear that we don't want to waste our lives (and risk our jobs) by writing a transaction manager. Wouldn't it be great if we could go one step further and not write a single line of code about transactions and have them magically handled by the infrastructure? Not only would that mean fewer lines of code to understand and maintain, but it would guarantee that all our code made a consistent set of assumptions about the transactional semantics of the application. This would, in turn, make reusing the application componentry much easier without having to go back to the design docs (or worse, the code) and decipher what the underlying intentions and assumptions were.

Happily, they thought of all that when J2EE was invented, and the EJB container is equipped not only to manage persistence and security, but transactions too. In fact, not only is it equipped to manage transactions, but for entity beans it's mandatory that the container manages the transactional behavior - bean-managed transactions are only an option for session or message-driven beans (MDBs), but I'm getting ahead of myself.

What Are the Options?
In general in the EJB world, transactions can be container or bean managed. As you would expect, for container-managed transactions (CMTs), all the code to control the starting, committing, and aborting of transactions is provided and managed by the EJB container. For bean-managed transactions (BMTs), the bean implementer gets to use the JTA API set to control the transaction demarcation directly. As I mentioned, entity beans aren't permitted to use bean-managed transactions (presumably to encourage reuse of entity beans). In fact, the EJB specification states that any transaction in force when a BMT method is called should be suspended by the EJB container before the business logic is invoked. Thus, using BMT beans in various transactional contexts isn't possible.

Bean reuse is really maximized by using container-managed transactions. Additionally, when using message-driven beans, unless you use container-managed transactions, there can be no transactional integrity between the dequeuing of the JMS message the bean is about to process and any updates that the bean's onMessage method may cause to happen. You get the general picture.... Aside from those comments, I'll mention BMTs no further, since this article is about getting the application server to do the transactional work for you.

In the Beginning There Was the Transaction - Container Managed...
There are six different policies that can be associated with methods on a CMT bean: NotSupported, Required, Supports, RequiresNew, Mandatory, and Never. Code executed in methods marked NotSupported and Never will not execute in the context of an active transaction. If such a method is called in the context of a transaction, the transaction will be suspended in the NotSupported case and a RemoteException will be thrown to the caller in the Never case. Either way, any work done by the method will not cause more work to be added to a transaction.

Required and Mandatory methods, on the other hand, work in the context of an existing transaction. For the Required case, the container will start a new transaction before calling the method if no transaction is associated with the calling context. For the Mandatory case, if the method is called outside the context of a transaction, a TransactionRequiredException will be thrown. Methods marked RequiresNew will have a fresh transaction started for them by the container. Any caller's transaction will be suspended first. In either event, the method will always execute in the context of a transaction. Finally, the Supports policy allows the code to participate in any existing transaction context or in none, if it's called outside of a transaction scope.

As a general rule of thumb, I would consider it good practice to avoid the use of policies that leave you uncertain as to a method's transactional context. In particular, avoid Supports. In the same way that unintialized variables can cause hard-to-find bugs in systems (especially when code is reused) it's much better to state, "This must be used in a transaction" or "This can't be" rather than "Well, I'm not really sure."

So What Happened in the End?
So, it's all very well. You've told the container when to start transactions for you, but it can't see your business logic.... How does it know when a transaction should end, and whether it should end with a commit or an abort? In the general case, if the container started a transaction, "T," before invoking a method, "M," then it will commit "T" before returning the results of the Method to the requestor.

There are two exceptions to this behavior. The first occurs when the method throws a system exception. The second, an application exception, "should be used to communicate application-level problems to the client, such as "You can't withdraw that much money, it would put you in overdraft."

There's no reason for the container to assume you want to roll back a transaction because of an application exception. It's a common misconception that throwing any exception from a method will cause the current transaction to be rolled back. It won't. A System exception is an exception not covered by the application exception category. These typically indicate catastrophic technical failures - "I couldn't get a database connection", for example. If one of these is thrown, the transaction will be rolled back (or marked for rollback, if the container didn't start it). Technically, the container considers any exception that is a subclass of RuntimeException or RemoteException to be a system exception.

So, what if you want the current transaction to roll back, but you want to throw an application exception? Well, there's a method on the EJBContext interface called setRollbackOnly(). This method will mark a transaction rollback only, and if the transaction was started by the container, then calling this method from your business logic indicates that the transaction should be rolled back rather than committed when the method returns.

While we're on the subject, there's another EJBContext method that pertains to transactions: getRollbackOnly(). Clearly, if your bean has been called in the context of a transaction that's already doomed, then there's no point wasting lots of CPU cycles doing some complex calculation with results that will only be rolled back and thrown away. If your beans contain such CPU-intensive code, then you can introduce a good optimization only by checking if the transaction is marked rollback before you execute it.

Got the Message?!
So that's transactions and beans. Now, one final word about message-driven beans. For CMT message-driven beans, the dequeuing of the JMS message that gets passed to your bean's onMessage method is done in the same transaction context that your method is invoked in. If your code causes the transaction to be rolled back, by any of the means discussed above, then (thanks to the transaction manager and its good old ACID properties), it will be as if the message never got dequeued.

Of course, if the message hasn't been dequeued then it's still on the queue waiting to be consumed so the very next thing that will happen is that it will be dequeued and redelivered to your waiting onMessage method, which will throw an exception, the transaction will be rolled back... ad infinitum.

So be careful if you're writing MDBs - better to write errant messages to some dead-letter queue for your application and commit the transaction than throw an exception and abort it. Unless, that is, you get some kind of warped pleasure from watching app servers spinning around infinite loops. WebLogic's JMS implementation also provides some configurable parameters to handle this case, to delay redelivery of a rolled-back message, or to automatically place it on a dead-letter queue after some number of retries.

That's all for now. The nice men in white coats are coming to commit me but remember - if you're using an app server it should be barking, not you.... See you next month.

More Stories By Peter Holditch

Peter Holditch is a senior presales engineer in the UK for Azul Systems. Prior to joining Azul he spent nine years at BEA systems, going from being one of their first Professional Services consultants in Europe and finishing up as a principal presales engineer. He has an R&D background (originally having worked on BEA's Tuxedo product) and his technical interests are in high-throughput transaction systems. "Of the pitch" Peter likes to brew beer, build furniture, and undertake other ludicrously ambitious projects - but (generally) not all at the same time!

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...