As a J2EE developer/administrator, you might have heard about GlobalTransaction or UserTransaction(UT), which is a specification that
J2EE prescribes to build transactional enterprise applications. In this blog, I will only discuss the relationship it has with J2C Connections/Database
When a connection is requested under a global transaction, by default, the connection has affinity towards that transaction. This means that a
connection, that is reserved under a certain transaction, is visible only to that transaction even if it is closed explicitly by the application.
This state remains as is until the enclosed transaction ends(either commits/rollbacks).
You might be wondering what benefit might it get if a connection is kept unused though it is explicitly closed? You have a valid question. But, there are
other school of applications which access database multiple times to complete business logic execution with in a single transaction. In those scenarios, the said
behavior acts as a connection cache keyed by transaction context. So, it would be relatively faster to fetch a connection from its transaction cache than
getting it from a pool. It is exactly for the same reason such an approach is taken by websphere to boost the application performance.
Another interesting question you might ask is "In my application I don't use UserTransaction; should I really care about it?". The answer is "YES". In the absense
of UT, websphere transparantely proives what is known as "Local Transaction Containment(LTC)". This LTC is created by containers before executing application
components such as service method of a Servlet or business method of an EJB. So, if you acquire a connection in a servlet service method, then the connection
is by default associated with LTC. Even if you close the connection explicitly using con.close() method, the connection is not freed until the service method
is completed. Sometimes, it may cause leak in the connection pool and finally make other requests wait for the connection.
How to avoid such an anamoly?
It is simple. Change the connection sharing mode to UNSHAREABLE. By default it is SHAREABLE. You can find this setting under <Resource- Ref> of module level Deployment Descriptor in your application(web.xml, ejb-jar.xml). You can configure <RES-SHARING-SCOPE> to suite your needs.
<res-sharing-scope>Shareable</res-sharing-scope> <!--- your change must go here -->
How do I decide?
First, analyze if your application asks for connection multiple times with in a UT or LTC. If yes, then go with the default behavior. Perhaps, that is
the optimal setting for your application. Otherwise switch to UNSHAREABLE behavior as explained above.
The postings on this site are my own and don't necessarily represent IBM's positions, strategies or opinions.