WebSphere Application Server Version 6.1 Feature Pack for Web Services
             Operating Systems: AIX, HP-UX, i5/OS, Linux, Solaris, Windows, z/OS

             Personalize the table of contents and search results

Example: Using connections with asynchronous beans

An asynchronous bean method can use the connections that its creating Java 2 Platform Enterprise Edition (J2EE) component obtained using java:comp resource references.

For more information on resource references, see the topic References. The following is an example of an asynchronous bean that uses connections correctly:

class GoodAsynchBean
{
	DataSource ds;
	public GoodAsynchBean()
		throws NamingException
	{
		// ok to cache a connection factory or datasource
		// as class instance data.
		InitialContext ic = new InitialContext();
		// it is assumed that the created J2EE component has this
		// resource reference defined in its deployment descriptor.
		ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDataSource");
	}
	// When the asynchronous bean method is called, get a connection,
	//  use it, then close it.
	void anEventListener()
	{
		Connection c = null;
		try
		{
			c = ds.getConnection();
			// use the connection now...
		}
		finally
		{
			if(c != null) c.close();
		}
	}
}

The following example of an asynchronous bean that uses connections incorrectly:

class BadAsynchBean
{
	DataSource ds;
	// Do not do this. You cannot cache connections across asynch method calls.
	Connection c;

	public BadAsynchBean()
		throws NamingException
	{
		// ok to cache a connection factory or datasource as
		// class instance data.
		InitialContext ic = new InitialContext();
		ds = (DataSource)ic.lookup("java:comp/env/jdbc/myDataSource");
		// here, you broke the rules...
		c = ds.getConnection();
	}
	// Now when the asynch method is called, illegally use the cached connection
	// and you likely see J2C related exceptions at run time.
	// close it.
	void someAsynchMethod()
	{
		// use the connection now...
	}
}



Related concepts
Asynchronous beans
References
Related tasks
Using asynchronous beans
Reference topic    

Terms of Use | Feedback

Last updated: Nov 25, 2008 2:35:59 AM CST
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.wsfep.multiplatform.doc/info/ae/asyncbns/xmp/xasb_connections.html