Ibm

Understanding connection transitions: Avoiding multi-threaded access to a JCA connection in WebSphere Application Server


developerworks3 retweets
Understanding connection transitions: Avoiding multi-threaded access to a JCA connection in WebSphere Application Server

Keep me signed in.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Display name:

All information submitted is secure.

Anoop Ramachandra is a Senior Staff Software Engineer in IBM India Software Labs. He has over eight years of experience on WebSphere Application Server product as a Technical Lead, developer and Level 3 support engineer. His major areas of expertise in WebSphere Application Server include System Management, Java EE Connector Architecture, Virtual Member Manager, Scheduler and Asynchronous beans. He is an IBM Certified System Administrator for WebSphere Application Server.

Rispna Jain is a Technical Software Deployment Manager for WebSphere suite of products in IBM Global Technology Services and works with clients in North America. She has seven years of experience on WebSphere Application Server product development at IBM Software Group in various roles such as development, L3 support and test. Rispna has also been a technical speaker for WebSphere Application Server related topics at various WebSphere conferences. She is an IBM Certified SOA associate and holds a Master of Technology degree in Computer Science.

Summary:  IBM® WebSphere® Application Server JCA connection manager provides connection pooling and enables administrators to establish a pool of connections that can be shared by applications running on an application server. However, the sharing of a JCA connection across multiple threads by an application can result in various exceptions. This article describes some of the application coding practices that lead to connection sharing across multiple threads, and explains the multi-threaded detection capabilities provided by WebSphere Application Server. This content is part of the IBM WebSphere Developer Technical Journal .

Level:  Intermediate

Activity:  1809 views

The IBM WebSphere Application Server connection pool helps to alleviate connection management overhead as well as decrease development tasks for data access. With WebSphere Application Server connection pooling, most user requests do not incur the overhead of creating a new connection because the data source can locate and use an existing connection from the pool of connections. The WebSphere Application Server connection manager supports both unshareable and shareable connections and manages the state of connection objects between the free pool and shared/unshared pool. It also provides local transaction containment (LTC) in an unspecified transaction context.

To use connections effectively and to avoid any multi-threaded access to a connection in an application, it is important to understand connection transitions between the free pool and shared/unshared pool with respect to transactions. These concepts are described in detail in this article.

A connection handle is a representation of a physical connection and is not the physical connection to the back end resource manager. A connection handle is returned by the connection manager when the getConnection() method is invoked from an application.

An unshareable connection cannot be shared with other components in an application. The component using this connection has full control over it. Access to a resource marked as unshareable means that there is a one-to-one relationship between the connection handle that a component is using and the physical connection with which the handle is associated. This access implies that every call to the getConnection() method returns a connection handle solely for the requesting user.

The use of a shareable connection means that, if conditions allow it, different getConnection() requests by an application will actually receive a handle for the same physical connection to the resource. The physical connection is shared through multiple connection handles instead of retrieving a new physical connection from the connection pool for every getConnection() invocation.

Factors that determine sharing include:

each getConnection() request should have the same connection properties.

each getConnection() request should be made within the same sharing scope.

Connection sharing conditions are such that a connection can be shared only within a sharing scope. The most common sharing scope is a transaction scope where multiple active connection handles can share the same physical connection. There are two transaction scopes in WebSphere Application Server:

Global transaction

Local transaction containment (LTC)

Within an LTC boundary, there cannot be multiple active connection handles that use the same physical connection. However, the physical connection can be reused if the previous connection handle that wraps the same physical connection is closed.

Connection reuse occurs when this pattern is used:

Get connection 1 -> use connection 1 -> commit/rollback connection 1 (optional) -> close connection 1 -> get connection 2 -> use connection 2 -> commit/rollback connection 2 (optional) -> close connection 2 ->...

The conditions causing the transition of a connection from the shared/unshared pool to free pool are illustrated in Figure 1; Table 1 explains the terms shown in the figure. The conditions are:

When an application invokes close() method on a connection in the unshared pool, the connection is returned to the free pool, if "AutoCommit" is set to true and there are no other references to the connection held by the application or Connection Manager.

When an application invokes close() method on a connection in the shared pool and the LTC or global transaction is still active, the connection is not returned to the free pool. The connection remains in the shared pool and can be reused within the transaction. The connection is returned to the free pool when the LTC or global transaction ends.

Unshared Pool

Free Pool

Close()

Local Transaction Containment (LTC)

Application which operates outside of a global transaction acquires a default context in WebSphere Application Server called LTC.

Global Transaction (GT)

A global transaction context might be created automatically for EJB methods by using container managed transaction support and specifying an appropriate transaction attribute for the method. The Java Transaction API (JTA) UserTransaction interface can also be used to create a global transaction context from within a servlet, a message driven bean, or an EJB component that specifies the use of bean managed transactions. Within a global transaction, multiple resource managers can be accessed and the transaction manager will coordinate among all the resource managers to ensure the atomicity of updates.

Table 2 explains the state of a connection when an application invokes the close() method on connection object, releasing a connection to free pool.

Transition

Shared

True

True

False

Connection does not return to the free pool. The sharing scope is the transaction and until the LTC ends, the connection will not be returned to the free pool.

False

True

False

Changing the Autocommit value will not affect the release of shared connection from shared pool to free pool. Only when transaction ends the shared connection is returned to the free pool.

True/False

False

True

Within a global transaction, the database ignores the Autocommit setting. Transaction Manager takes care of commit or rollback as per application call, and once the transaction ends the connection is returned back to the free pool.

Unshared

True

True

False

False

True

False

If Autocommit is set to false, then the connection cannot be returned back to the free pool. Application has to invoke commit on connection object explicitly prior to closing the connection. This would return the connection back to free pool.

True/False

False

True

Connections are returned back to the free pool when the connection is closed and global transaction ends. The Autocommit setting is ignored.

This section describes some scenarios that could lead to multi-threaded access to a connection. These scenarios have been recreated with WebSphere Application Server V7.0 and V8.0 using and IBM DB2 database.

import java.sql.*; import javax.naming.*; import javax.sql.*; public class Test extends Thread{ static Connection conn = null ; static DataSource ds = null; public static void main (String args []) { try{ Context initialContext = new InitialContext(); ds = (DataSource)initialContext.lookup("java:comp/env/test"); //get connection from datasource conn = ds.getConnection(); }catch (Exception e) { // handle exception e.printStackTrace(); } int NUM = 5; // create multiple threads Thread[] multithread = new Thread[NUM]; // spawn threads for (int i = 0; i < NUM; i++) { multithread[i] = new Test(); multithread[i].start(); } } public void run() { // Create a Statement try{ Statement stmt = conn.createStatement (); ResultSet rs = stmt.executeQuery ("select * from EMPLOYEE"); stmt.close(); rs.close(); conn.close(); }catch (Exception e){ //handle exception e.printStackTrace(); } } }

In this scenario, when one thread closes the connection, the other threads operating on the same connection will be affected. This could result in the exception shown in Listing 2.

Exception description (Listing 2): Attempted to perform an operation on a Statement object that is already closed. Retrieve a new instance of the Statement object on which to perform the operation.

The exception shown in Listing 3 could also be thrown.

Exception description (Listing 3): Attempted to perform an operation on a Connection object that is already closed. Retrieve a new instance of the Connection object on which to perform the operation.

Application code should not pass a cached connection handle from one instance of a data access client to another client instance. Transferring the connection handle between client instances creates the problematic contingency of one instance using a connection handle that is referenced by another.

For example, when the application code of a client instance that receives a transferred handle closes the handle and the client instance that retains the original reference to the handle tries to reclaim it, the application server issues an exception.

Listings 4 and 5 shown some exceptions expected in this case.

Exception description (Listing 4): An exception was detected cleaning up the ManagedConnection for a destroy operation. Refer to the error reported by the database software to help determine the cause of the error.

Exception description (Listing 5): An exception was detected while closing JDBC Connection which was already closed.

public void example { Connection Conn=null; // other methods protected void finalize() throws Throwable { conn.close(); }

There could also be a problem if a JDBC object is not closed by the thread that is using the object. An example of such a scenario is when a reference to this JDBC object is stored in a different object and the reference is closed by a finalize() method during garbage collection.

The exception that could be thrown here is shown in Listing 7.

Exception description (Listing 7): The connection manager caught an exception while trying to perform an operation on a ManagedConnection.

import java.sql.*; import javax.naming.*; import javax.sql.*; #sql context CtxSqlj; // Create connection context class CtxSqlj Context ctx=new InitialContext(); DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb"); Connection con=ds.getConnection(); String empname; // Declare a host variable con.setAutoCommit(false); // Do not autocommit CtxSqlj myConnCtx=new CtxSqlj(con); // Create connection context object myConnCtx #sql [myConnCtx] {SELECT LASTNAME INTO :empname FROM EMPLOYEE WHERE EMPNO='000010'}; // Use myConnCtx for executing an SQL statement myconnCtx,close(KEEP_CONNECTION);

In Listing 8, KEEP_CONNECTION is a constant that can be passed to the close() method. It indicates that the underlying JDBC Connection object should not be closed.

The application must close the SQLJ connection context when it is done using it. Closing the context must be done with the KEEP_CONNECTION option set to false, as shown in Listing 9.

public static final boolean KEEP_CONNECTION=false; myContext.close(KEEP_CONNECTION);

Failure to close the context with the KEEP_CONNECTION option will result in an exception in WebSphere Application Server as illustrated in Listing 10.

Exception description (Listing 10): Attempted to perform an operation on a Connection object that is already closed. Retrieve a new instance of the Connection object on which to perform the operation.

/** * Servlet implementation class ServletTest */ public class ServletTest extends HttpServlet { Connection conn=null; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ Context initialContext = new InitialContext(); DataSource ds1 =(DataSource)initialContext.lookup("java:comp/env/test"); if (conn==null){ conn = ds1.getConnection(); Statement stmt = conn.createStatement (); ResultSet rs = stmt.executeQuery ("select * from EMPLOYEE"); conn.close(); } else { Statement stmt = conn.createStatement (); ResultSet rs = stmt.executeQuery ("select * from EMPLOYEE"); conn.close (); } }catch(Exception e ) { // handle the exception e.printStackTrace(); } } }

Once the connection handle is closed, the next servlet request, which is a new thread, would try to create a statement on same closed handle and fail with ObjectClosedException, shown in Listing 12.

Exception description (Listing 12): Attempted to perform an operation on a Connection object that is already closed. Retrieve a new instance of the Connection object on which to perform the operation.

com.ibm.websphere.ce.cm.ObjectClosedException: DSRA9110E: Connection is closed. [2/14/12 11:55:07:768 IST] 0000001c SystemErr R at com.ibm.ws.rsadapter.jdbc.WSJdbcWrapper.createClosedException(WSJdbcWrapper.java:109) [2/14/12 11:55:07:768 IST] 0000001c SystemErr R at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.activate(WSJdbcConnection.java:2812) [2/14/12 11:55:07:768 IST] 0000001c SystemErr R at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.createStatement(WSJdbcConnection.java:1605) [2/14/12 11:55:07:768 IST] 0000001c SystemErr R at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.createStatement(WSJdbcConnection.java:1585)

Invoking the close() method on the connection handle frees up the connection to the free pool, and the connection handle will still be available for reuse when getConnection() method is called on the data source.

When the close method is not invoked on the connection handle, the connection is released to the free pool at the end of the LTC and the connection handle is dissociated from the connection.

public class ServletTest extends HttpServlet { Connection conn=null; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Context initialContext = new InitialContext(); DataSource ds1 = (DataSource)initialContext.lookup("java:comp/env/test"); conn = ds1.getConnection(); Statement stmt = conn.createStatement (); //Database hang or network problem rs = stmt.executeQuery ("select * from EMPLOYEE"); rs.close(); stmt.close(); } catch (Exception e) { // handle exception e.printStackTrace(); } } }

Any subsequent request using the same connection handle will result in the exception illustrated in Listing 14.

Exception description (Listing 14): Attempted to perform an operation on a Connection object that is already closed. Retrieve a new instance of the Connection object on which to perform the operation.

public class ServletTest extends HttpServlet { ResultSet rs= null; Connection conn = null; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ Context initialContext = new InitialContext(); DataSource ds1 = (DataSource)initialContext.lookup("java:comp/env/test"); conn = ds1.getConnection(); if(rs==null){ Statement stmt = conn.createStatement(); rs = stmt.executeQuery("select * from EMPLOYEE"); } System.out.println(rs.next()); } catch (Exception e) { // handle exception e.printStackTrace(); } } }

When the LTC ends, the connection is returned back to the free pool, and child objects of the connection including the ResultSet are closed. Therefore, any new request to access the cached ResultSet would encounter the exception shown in Listing 16.

Exception description (Listing 16): Attempted to perform an operation on a ResultSet object that is already closed. Retrieve a new instance of the ResultSet object on which to perform the operation.

Get a connection

Commit a global transaction

Use the connection again

Be aware that, Statements, PreparedStatements, and ResultSets are closed implicitly after a transaction ends, while the connection remains valid. Table 3 lists the valid and invalid sequence of actions in this scenario.

start transaction

start transaction

get connection

get connection

use connection

use connection

Close connection

Commit transaction

Commit transaction

start new transaction

start new transaction

use connection

use connection

close connection

close connection

commit transaction

commit transaction

Related topics

Here are some of the custom properties and configurations in WebSphere Application Server that affect multi-threaded access to a connection.

DisableMultiThreadedServletConnectionMgmt is a custom property that is meant to allow connections to be reused across servlets. This property can be set as a web container custom property (Figure 3). In the administrative console, navigate to Application servers > server_name > Web container > Custom properties. Create a property named DisableMultiThreadedServletConnectionMgmt and set its value to true.

With this property enabled, if the connection handle is not closed and the servlet ends, the web container, as part of postinvoke, parks the connection and does not close the connection handle.

To enable a non-transactional data source, navigate form the administrative console to Data sources > datasource_name > WebSphere Application Server data source properties.

Select the Non-transactional data source checkbox (Figure 4).

In WebSphere Application Server V7.0 and later, an LTC can be shareable; that is, a single LTC can span multiple application components, including web application components and enterprise beans that use container-managed transactions, so that these components can share connections without using a global transaction.

This can be achieved by setting the Shareable attribute in the deployment descriptor of each component.

When you set the Shareable attribute, the extended deployment descriptor XML file includes the line shown in Listing 17.

To enable this property using the administrative console, navigate to Resources > JDBC > JDBC providers > JDBC_provider > Data sources > data_source name > WebSphere Application Server data source properties, and select the check box to enable this property (Figure 6).

Anoop Ramachandra is a Senior Staff Software Engineer in IBM India Software Labs. He has over eight years of experience on WebSphere Application Server product as a Technical Lead, developer and Level 3 support engineer. His major areas of expertise in WebSphere Application Server include System Management, Java EE Connector Architecture, Virtual Member Manager, Scheduler and Asynchronous beans. He is an IBM Certified System Administrator for WebSphere Application Server.

Rispna Jain is a Technical Software Deployment Manager for WebSphere suite of products in IBM Global Technology Services and works with clients in North America. She has seven years of experience on WebSphere Application Server product development at IBM Software Group in various roles such as development, L3 support and test. Rispna has also been a technical speaker for WebSphere Application Server related topics at various WebSphere conferences. She is an IBM Certified SOA associate and holds a Master of Technology degree in Computer Science.

Thank you. This entry has been flagged for moderator attention.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Display name:

(Must be between 3 – 31 characters.)

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

publish-date=05092012

Tags

Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Search all tags

Experience today!

DRS in images

Antonio Lobato's Twitter Photo

Picture of daguilar6
24 Apr 2012
116 retweets
No hace falta ser Fernando Alonso para ir rapido... Y sin KERS ni DRS!!

Tiny baby after being brought home from hospital, dr'...

http://twitpic.com/90r73j

Tiny baby after being brought home from hospital, dr's told parents she needs oxygen mask #bahrain
Tiny baby after being brought home from hospital, dr's told parents she needs oxygen mask #bahrain

Picture of daguilar6
25 Mar 2012
110 retweets

Twitpic - Share photos and videos on Twitter

http://twitpic.com/5h8tft

Twitpic - Share photos and videos on Twitter
現在、近くにTVがない方のために、F1マシンのDRS(可変ウィング)の絵を描いておきました。絵の矢印の部分です。ご参考まで!

Picture of daguilar6
27 Jun 2011
74 retweets

DRS in videos

F1 1979 René Arnoux Vs Gilles Vileneuve

Picture of daguilar6
6 Mar 2009
1K retweets
3 dk ayırın ve tarihin en iyi 2.lik savaşını seyredin.Arnoux-Villeneuve Dijon 1979 DRS'ye kimin ihtiyacı var? :-)

عامر عبدالله/ جمهوركم السعودي غيير HD

Picture of daguilar6
17 Aug 2011
1K retweets
@mutaiwee باختصار هذا ماقاله عامر عبدالله عن الجمهور السعودي في أحد المقابلات

VMware vSphere Training: Migration Hot & Cold Migrati...

Picture of daguilar6
27 Apr 2012
1K retweets
vSphere 101: Migration Hot & Cold Migration - DRS. How to create vSphere DRS clusters [video]

DRS in articles

The BALANCE: DJ DiBIASE v. DJ RAPKO: May 11th Edition...

Picture of daguilar6
14 Apr 2012
23 retweets
@djjamad TONIGHT! #theBALANCE @ 595NORTH w/ @DJSense @djjamad @tompatl & @zip_kennedy DRS @ 10p! RT @DRESthaBEATnik

awesome-excoties

http://awesome-excoties.blogspot....

awesome-excoties
is couldn't get any cooler! DRS Erica

Picture of daguilar6
26 Dec 2011
9 retweets

awesoom

http://awesoom-tee.blogspot.com...

awesoom
WTF? is a jackpot find! DRS Jason's Lyric Home Alone Chrissy

Picture of daguilar6
26 Dec 2011
3 retweets

DRS in sites

YouTube - Broadcast Yourself.

http://youtube.com/das_captcha?ne...

Vorgeschlagene Sprache (von uns festgelegt): Deutsch Vorgeschlagene Standorteinstellung (von uns festgelegt): Deutschland Durch den Standortfilter werden in Listen wie Meistgesehen und in den Suchergebnissen Videos aus diesem Land bzw. dieser Region angezeigt. Du kannst die einzelnen Einstellungen über die Links unten in der Fußzeile ändern. Klicke auf "OK", um die Einstellung zu übernehmen, oder auf "Abbrechen", um "English (US)" als Sprache und "Weltweit (alle)" als Standortfilter festzulegen. Ab...

Picture of daguilar6
25 Mar 2012
1K retweets

Tribunnews.com - Berita Terkini Indonesia

http://Tribunnews.com

Suyadi Tak Akan Kembali Memerankan Pak Raden: Drs Sayudi mengungkapkan d... Local Breaking News

Picture of daguilar6
15 Apr 2012
1K retweets

Oregon Local News, Breaking News, Sports & Weather - ...

Picture of daguilar6
1 Jan 1970
1K retweets
DRS. OZ AND ROIZEN: Three smart steps around diabetes