Sharing connections in WebSphere Application Server V5

This article describes how to share connections in WebSphere Application Server V5 and presents programming models among different applications, such as Web applications, session EJBs, BMP EJBs, and CMP EJBs.

Teresa Kan, IBM WebSphere Architecture and Development

Teresa Kan is a team leader and an architect in the WebSphere Application Server software development area. She is responsible for the design of the Relational Resource Adapter that provides the persistent mechanism for WebSphere J2EE applications to access the relational databases. Teresa has a MS in Computer Science from Utah State University.



Jian Tang (jian.tang@us.ibm.com), IBM WebSphere Development

Jian Tang works on the WebSphere Application Server Relational Resource Adapter team, which provides relational database connectivity for WebSphere applications. Jian has a Master's degree from the University of Nebraska - Lincoln.



14 April 2004

Introduction

Sharing connections in IBM® WebSphere® Application Server V5 (V5.0, V5.0.1, V5.0.2) can reduce resource allocation costs and deadlock scenarios. This article describes how to share and reuse connections in WebSphere Application Server V5 and the tradeoffs of sharing or not sharing connections. It also presents programming models to share connections among different applications, such as Web applications, session EJBs, BMP EJBs, and CMP EJBs. In addition, a WebSphere Studio Application Developer example shows how to set access intent and isolation level in a resource reference.

The Java 2 Enterprise Edition (J2EE) 1.3 specification introduces a new concept, resource sharing scope, identified by the deployment descriptor element, res-sharing-scope, in the application deployment descriptor. J2EE application components can use this deployment descriptor element to indicate whether a connection to a resource manager is shareable or unshareable. If the value of res-sharing-scope is set to unshareable, connections acquired from this resource are not shareable. Otherwise, connections acquired from this resource are shareable.

WebSphere Application Server (hereafter called Application Server) V5.0.x (includes V5.0, V5.0.1, V5.02) is a J2EE 1.3-compliant application server. It supports both shareable and unshareable connections.

Terminology

A connection handle is used in a J2EE application. It is not the physical connection to the backend resource manager; it is a proxy of the physical connection. A physical connection is the connection object returned from the JDBC driver. You can think of a connection handle as a wrapper object of a physical connection. Having "shared connections" means having multiple connection handles that share the same physical connection.

Access to a resource marked as unshareable means that there is a one-to-one relationship between the connection handle a component is using and the handle's physical connection. This access implies that every call of getConnection returns a connection handle whose physical connection is solely for the requesting user. Typically, you must choose unshareable if the connection results in unexpected behavior of another application that is sharing the connection (for example, changing the isolation level).

Marking a resource as shareable allows for greater scalability. Instead of retrieving another physical connection on every getConnection invocation, the physical connection is shared through multiple connection handles if certain conditions are met. However, sharing a connection means that each user cannot change the connection and disrupt a sharing partner (for example, changing the isolation level).

The next section, "Sharing physical connections", describes the requirements to make acquired connection handles share the same physical connection. The Programming model section discusses the tradeoffs of sharing connections and describes how different application modules share the same physical connection from a programming model's perspective, and how sharing impacts the programming model. The Setting the resource reference isolation level section presents an example of how to set the res-sharing-scope, how to set the transaction isolation level when creating resource reference, and how to set access intent for applications.

Sharing physical connections

Sharing a connection can only happen 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 Application Server V5: global transaction and Local Transaction Containment (LTC) boundary.

  • A global transaction is either a user transaction initiated by the J2EE application, or a container global transaction initiated by the Application Server Enterprise Java Bean (EJB) container. The EJB container starts a global transaction when the EJB methods are configured with the Required or RequiresNew transaction attribute. The EJB container may also use the client's global transaction when an EJB method is configured with the Required, Supports, or Mandatory transaction attributes. Note that a client to the EJB is either a J2EE application, servlet, JSP, or another EJB.
  • An LTC boundary is different from the Resource Manager Local Transaction (RMLT), which is a resource's view of a local transaction. An LTC is a scope in which multiple RMLTs may be accessed. LTC is always established by the container in the absence of a global transaction. An example of a LTC is an execution of a bean method with the transaction attribute NotSupported. An example of RMLT is setting an autocommit to false and later committing the connection.

In Application Server, a connection sharing scope is a global transaction. Although multiple getConnection calls in a LTC may return multiple connection handles with the same physical connection, the physical connection are serially reused, but not shared. This behavior is "connection serial reuse." Connection serial reuse within LTC is discussed later.

As mentioned above, if an application's deployment descriptor element res-sharing-scope is set to shareable, multiple getConnection calls in the application are eligible to share the same connection if certain conditions are met. For multiple getConnection calls to return the same physical connection within a sharing scope, the following connection properties must be the same:

  • Java Naming and Directory Interface (JNDI) name. While the JNDI name is not actually a connection property, this requirement means that you can only share connections from the same data source within the same server process. You must call two getConnection calls on the same data source in the application server to share a physical connection.
  • Resource authentication setting. Use the resource authentication setting of the resource reference to specify how an application component provider associates a principal (user ID and password) to a resource manager. For non-CMP applications, the resource authentication is identified by the res-auth deployment descriptor. Its value is either Application or Container. Application Server also offers an IBM extension for resource authentication for a CMP connection factory. This setting is identified by the resAuth element in the IBM deployment descriptor extension file, ibm-ejb-jar-ext.xmi. You can set the value of resAuth to either Per_Connection_Factory or Container. Per_Connection_Factory corresponds to the Application value of the res-auth deployment descriptor. When two data sources or connection factory references are associated with one data source in Application Server, connections are shareable if and only if these two references have the same resource authentication value. For a description on resource authentication, refer to Database authentication in WebSphere Application Server V5.
  • Principal. The same principal means the same user and password are required for relational databases. If applications use a different user ID and password to acquire the connection, the physical connections returned from the getConnection calls will be different. When an application's resource authentication setting is set to Application, you can acquire the connections by either getConnection() or getConnection(String userid, String password). Notice that the connections acquired from these two calls are not shared, even if the component-managed authentication alias associated with the datasource has the same user id and password used in getConnection(String userid, String password).
  • Connection transaction isolation level property. In Application Server, you can specify what isolation level the acquired connection uses in several ways:
    • You can use access intent to specify the transaction isolation level.
    • You can use an IBM extension (specified as isolationLevel in the IBM extension file ) to specify the transaction isolation level of a particular application's data source reference.
    • You can set the transaction isolation level to an IBM extended API (JDBCConnectionSpec) and then use WSDataSource.getConnection(JDBCConnectionSpec) to acquire the connection. To share the same physical connection, the transaction isolation levels of multiple getConnection calls within a given transaction must be the same. Note that the IBM extended API, JDBCConnectionSpec, is a proprietary API. If you use this API, your application does not port to other application servers.
  • Connection readOnly, catalog, and typeMap properties. Just as the connection transaction isolation level, these three connection properties must be the same for multiple getConnection calls to share the same physical connection. Applications can use JDBCConnectionSpec to specify the values of these three properties.

If one of the above requirements is not met, two getConnection calls will return different physical connections.

Listing 1 shows two connection handles sharing the same physical connection within a user transaction. The resource sharing scope of the resource reference is set to Shareable. Connections conn1 and conn2 are two connection handles acquired from the same data source, ds. Since these two connections are acquired in one sharing scope (in this case, a user transaction), and all the sharing requirements are met, conn1 and conn2 share the same physical connection.

If the res-sharing-scope deployment descriptor element is set to Unshareable in an application's deployment descriptor, the connections do not share the same physical connection. Multiple getConnection calls in one global transaction or LTC will return connection handles with different physical connections.

Listing 1. Sharing connections in one user transaction
// Start a user transaction
userTransaction.begin();

// Get the first connection
java.sql.Connection conn1 = ds.getConnection();
java.sql.Statement stmt1 = conn1.createStatement();
...

// Get the second connection
java.sql.conenction conn2 = ds.getConnection();
java.sql.Statement stmt2 = conn2.createStatement();
...

// Commit the user transaction
userTransaction.commit();

Connection Serial Reuse in LTC

Within a Local Transaction Containment (LTC) boundary, you cannot have multiple active connection handles that use the same physical connections. However, you can reuse the physical connection if the previous connection handle that wraps the same physical connection is closed. Connection reuse occurs when you use the following pattern:

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 connection returned from the second getConnection has the same physical connection as that returned on the first getConnection, provided that the same properties are used and the res-sharing-scope is not set to unshareable. Because the connection use is serial, only one connection handle to the underlying physical connection is used at one time, so true connection sharing does not take place. Therefore, the physical connection is "serially reused." Note that committing or rolling back connection is optional in this pattern.That is, even if the first connection is not committed or rolled back, the second getConnection still returns the same physical connection once the previous connection is closed.You must pay attention to the transaction semantics behind the following statement: "The rollback or commit of connection handle 2 will rollback or commit the work done to connection handle 2. It will also rollback or commit the work done to connection handle1."

Listing 2 shows two connection handles reuse the same physical connection in one LTC. This code is either in a Web application (servlet) or in an EJB method that is not executed in a global transaction boundary. In the absence of the global transaction boundary, a LTC boundary is established. In this application, connection conn1 is acquired from datasource, ds, and then the autocommit value of connection conn1 is set to false. Then record 1 is inserted to the database. After that, connection conn1 is closed without committing or rolling back the connection. Connection conn2 is then acquired from the same datasource, ds. Since the connection properties used to acquire connection conn2 are the same as those used to acquire connection conn1, and connection conn1 is closed, the same physical connection is reused for connection conn2. After that, the autocommit of conn2 is set to false (since the connection is reused, it is not necessary to set autocommit to false since it is already false), and then record 2 is inserted in the database. When connection conn2 is rolled back, not only is record 2 insertion rolled back, the record 1 insertion is also rolled back.

Listing 2. Reusing connection in a LTC boundary
// Get the first connection
java.sql.Connection conn1 = ds.getConnection();
conn1.setAutoCommit(false)
java.sql.Statement stmt1 = conn1.createStatement();

//use statement1  to  insert record 1
...  ...

conn1.close();

java.sql.conenction conn2 = ds.getConnection();
conn2.setAutoCommit(false);
java.sql.Statement stmt2 = conn2.createStatement();

//use statement 2 to insert record 2
...  ...

conn2.rollback();
conn2.close();

Programming model

Sharing connections make an application more scalable. It reduces resource allocation and reduces the chance of deadlock scenarios. However, there are limitations when sharing connections. For example, setting properties on shareable connections is not allowed because a user of one connection handle might not anticipate a change made by another connection handle. This limitation is part of the J2EE 1.3 standard.

In some cases, you do not want applications to share the physical connection. One reason is that applications may need to change connection attributes and these changes are not allowed for shareable connections. However, there are restrictions about using unshareable connections besides increasing the resource allocation costs.

Let us look at the code in Listing 1 again. Assume the resource reference of the data source is marked as Unshareable. Connection handles conn1 and conn2 will have different physical connections. This application may fail in one of the two following scenarios:

  • If the datasource does not supporting XA transactions, for example, the datasource is a non-XA capable datasource such as an implementation of javax.sql.ConnectionPoolDataSource, this application fails because two non-XA resources are not allowed to be enlisted in one global transaction. Application Server throws the following exception: "Method enlist caught java.lang.IllegalStateException (specific exception stack trace) while trying to enlist resources from datasource xxx with the Transaction Manager for the current transaction, and threw an Exception."
  • Even if the datasource supports XA transactions, there is a possibility of deadlock. For example, stmt1 tries to insert a record and stmt2 tries to update the same record. This leads to a database deadlock when the transaction isolation level of the connection is TRANSACTION_REPEATABLE_READ. In this case, you can either see an exception thrown from the database backend indicating a deadlock or transaction timeout, or a javax.transaction.TransactionRollbackedException after the transaction is timed out.

We recommend using shareable connections in Application Server. There are several ways to ensure that these EJBs and Web applications share the same physical connection. To share connections, set the res-sharing-scope deployment descriptor shareable. Note that CMP EJBs do not have this deployment descriptor. Connections used in CMP EJBs in Application Server V5 are always shareable. To share the connection in a sharing scope, use the same connection properties. Among these connection properties, transaction isolation level is a commonly used one.

There are several ways to specify the transaction isolation before acquiring the connection. For Bean Managed Persistence (BMP) and Container Managed Persistence (CMP) EJBs, you can use access intent to specify the transaction isolation level. For BMP EJB, session EJB, and Web applications, you can use IBM resource isolation level extension to specify the isolation level associated with the resource reference. For any JDBC application (including BMP EJB, session EJB, and Web application), you can set the transaction isolation level to a JDBCConnectionSpec object or use the same resource reference to acquire the connection. The following sections describe how you can use these alternatives to share connections among different applications.

Sharing a connection among session EJBs, BMP EJBs, and Web applications

Session EJBs, BMP EJBs and Web applications (servlet) follow the JDBC programming models. Sharing connections among these models occur as follows:

  • All these applications access the same data source references, which have the same IBM isolation level extension configuration or do not have the IBM isolation level extension configuration. When applications call getConnection() or getConnection(userid, password) with the same user id and password in one sharing scope, the returned connection handles share the same physical connection.
  • Applications can also use IBM extension WSDataSource.getConnection(JDBCConnectionSpec) with equal JDBCConnectionSpec objects to get the connection. These calls can return multiple connection handles with the same physical connection in one sharing scope. This API is an IBM extended API. If your applications use it, your applications does not port to other application servers.

Sharing a connection between CMP beans or methods

When two CMP bean methods use the same access intent, they share the same physical connection in one sharing scope. Different access intent policies trigger different physical connections to be allocated. For example, a CMP bean has two methods: method 1 is associated with wsPessimisticUpdate intent, whereas method 2 is associated with the wsOptimisticUpdate access intent. In this case, method 1 and 2 may not share the same physical connection within a sharing scope. In other words, an XA DataSource is required to run in a global transaction. You may experience deadlocks from a database if both methods try to access to the same table. Therefore, sharing a connection is determined by the access intents that are defined in the CMP methods.

Sharing a connection between CMP and BMP beans

To share a physical connection with a CMP bean, ensure that you have the same connection properties. Other than the isolation level, a CMP bean never specifies the ReadOnly, TypeMap, and Catalog properties on a connection. You cannot modify these properties on a BMP connection if you want to share the physical connection with a CMP bean.

There are three options to ensure that one CMP EJB and one BMP EJB share the same physical connection if both of them access the same datasource and use the same database authentication:

  1. Out-of-box scenario: If you do not specify any access intent on the CMP EJB and BMP EJB, and you do not specify the resource reference isolation level for the data source used in the BMP EJB, the connection properties will be the same if you use getConnection() method in the BMP EJB. The CMP EJB and BMP EJB share a connection if they are running in the same global transaction.
  2. Define the same access intent in both the CMP and BMP EJB methods: Since both methods use the same access intent, they share the same physical connection within a sharing scope. However, this BMP EJB is not portable because it uses the IBM extended API to associate an access intent. Listing 3 shows an example of BMP EJB application using the access intent to acquire the connection. In the BMP EJB application, you need to:
    • Look up a specific access intent service, aiService.
    • Get the access intent from the access intent service.
    • Get the transaction isolation level from the access intent.
    • Create a JDBCConnectionSpec object connSpec and set its transaction isolation level.
    • Use this JDBCConnectionSpec object to acquire the connection.

      The code shown in Listing 3 achieves backend transparency because it retrieves the transaction isolation level from the access intent. Your application can hardcode the transaction isolation level, but it is not portable to other backends because the same access intent corresponds to different transaction isolation level for different database backends (see Table 1 below). The next option is the most preferable one.

  3. Determine what isolation level of the access intent is used on a CMP EJB method, then use IBM isolation level extension specify the correspondent isolation level associated with the resource reference. A particular access intent has a certain transaction isolation level. Table 1 lists the corresponding transaction isolation levels for different database back-ends. The BMP EJB can set the transaction isolation level in its resource reference. If this transaction isolation level is the same as the one in CMP EJB's access intent, these two connections will share the same physical connection in one sharing scope. This option requires more manual process and the isolation level may be different from database to database. However, this option provides a more efficient and portable mechanism than option 2.
Listing 3. Sharing connections using IBM Extended APIs between CMP EJBs and BMP EJBs
// Look up the access intent service
AccessIntentService aiService = (AccessIntentService) getInitialContext().lookup(
     "java:comp/websphere/AppProfile/AccessIntentService");

// Get access intent from the access intent service
AccessIntent intent = aiService.getAccessIntent(myEntityCtx);

// Get the transaction isolation level from the access intent
int isoLevel =  WSCallHelper.getDataStoreHelper(ds).getIsolationLevel(intent);

// Create a JDBCConnectionSpec object and set the isolation level
JDBCConnectionSpec connSpec = WSRRAFactory.createJDBCConnectionSpec();
connSpec.setTransactionIsolation(isoLevel);

// Get connection using connection spec 
Connection conn = ((WSDataSource) ds).getConnection(connSpec);

Table 1. Mapping of AccessIntent profile to transaction isolation level in different database backends
AccessIntent profileDB2OracleSybaseInformixCloudscapeSQL ServerSelect for update
WSPessimisticUpdate-WeakestLockAtLoad (default policy)RRRCRRRRRRRRNo (Oracle-yes)
WSPessimisticUpdateRRRCRRRRRRRRYes
WSPessimisticReadRRRCRRRRRRRRNo
WSOptimisticUpdateRCRCRCRCRCRCNo
WSOptimisticReadRCRCRCRCRCRCNo
WSPessimisticUpdate-NoCollistionsRCRCRCRCRCRCNo
WSPessimisticUpdate-ExclusiveSSSSSSYes
  • RC = JDBC Read committed, RR = JDBC Repeatable read, S = JDBC Serializable
  • Oracle does not support JDBC Repeatable Read (RR). Therefore, wsPessimisticUpdate-weakestLockAtLoad and wsPessimisticUpdate behave the same way on Oracle as do wsPessismisticRead and wsOptimisticRead. Because of an Oracle restriction, the OracleXADataSource JDBC class cannot run with an S transaction isolation level. Do not use the WSPessimisticUpdate-Exclusive profile on a OracleXADataSource.
  • The ForUpdate column indicates whether the Select statement will have a ForUpdate clause for each profile.

Sharing a connection between CMP and JDBC application

The same method is used when sharing between a CMP and BMP bean methods. You can determine what isolation level of the access intent is used on a CMP EJB method, and then use IBM isolation level extension to specify the corresponding isolation level associated with the resource reference.

Setting the resource reference isolation level and access intent

This section shows how to set the resource sharing scope, how to set the IBM isolation level extension, and how to associate access intents with BMP and CMP EJBs.

Application example

The application example provided with this article is an Enterprise application file, BankCustomerEAR.ear. It has an EJB file, BankCustomerEJB.jar. This file has three EJBs: Session EJB AccountManagement, BMP EJB Customer, and CMP EJB Account. Session EJB AccountManagement acts as a session facade for Web applications or clients to access entity EJBs and thus supports the remote interface. The Customer and Account Entity EJBs only support local interfaces. One Customer EJB has zero or more Account EJBs. The Customer EJB accesses the table Customer, and the Account EJB accesses the table Account. Figure 1 shows the structure of the Customer and Account tables. Field customerId is the primary key of the Customer table, field accountId is the primary key of the Account table, and field customerId is the foreign key of the Account table.

Figure 1. Customer and Account tables
Customer and Account tables

All of the EJB methods are configured with the Required transaction attribute. Therefore, Entity EJBs accesses in any business method of the session bean AccountManagement are executed in a global transaction.

Suppose the application needs to model the following scenario. A customer can have a maximum of three accounts. If a customer tries to create a new account while he or she already has three accounts, the request is rejected.

When a customer tries to create a new account, the createAccount method of the Session EJB, AccountManagent, is called. It first gets the number of the accounts available. If the number is less than three, the account is created. If the number is more than or equal to three, it throws an exception.

The session bean calls the method getNumberOfBAccounts() on the Customer BMP EJB to get the customer' number of accounts. Listing 4 shows the code snippet of the createAccount method of the AccountManagement session bean.

Listing 4. Code snippet from createAccount method of AccountManagement session bean
public void createAccount(String customerId, String accountId, double balance)
        throws CreateException, FinderException, EJBException {
        CustomerLocal customer = customerHome.findByPrimaryKey(new CustomerKey(customerId));

        if (customer.getNumberOfAccounts() < ACCOUNT_NUMBER_LIMIT){
            accountHome.create(accountId, customerId, balance);
        }
        else {
            throw new EJBException("The maximum number of accounts has been reached.");
        }

Suppose the Account CMP EJB is configured with access intent WSPessimisticUpdate. Because DB2® is the chosen database, the connections used by Account CMP EJB have a transaction isolation level of REPEATABLE_READ.

In the method getNumberOfAccounts() of the Customer BMP EJB, a query is executed to the Account table to query the customer's number of accounts. The query is SELECT count(accountId) FROM Account WHERE customerId = ?.

As discussed in previous sections, to share the same connection for a Customer BMP EJB and an Account CMP EJB, the connection handling of transaction isolation levels should be the same. In method createAccount of the session EJB AccountManagement, both EJBs are used and both access the same table-Account table. It is important to make sure the BMP EJB and CMP EJB share the physical connection. Otherwise, a deadlock could occur.

Consider the case where the data source reference of the Customer BMP EJB is configured with SERIALIZABLE transaction isolation level. The physical connection used in getNumberOfAccounts() will be different from the connection used in the methods of the Account CMP EJB because the connection used in the Account CMP EJB has a REPEATABLE_READ transaction isolation level. When method createAccount is executed, a deadlock occurs because you get two connections with different isolation levels being used within the same transaction and these two connections access the same table Account. You see either a javax.transaction.TransactionRollbackedException or a transaction timeout exception.

To make the application work,simply configure the data source reference of Customer BMP EJB with the REPEATABLE_READ transaction isolation level.

To test both the deadlock case and the working case with the same application, configure the data source reference of the Customer BMP EJB with a REPEATABLE_READ transaction isolation level for the working case and a SERIALIZABLE transaction isolation level for the deadlock case.

The following section shows how to set the transaction isolation level of the data source reference and the access intent for the CMP EJBs and BMP EJBs. The example uses the WebSphere Studio Application Developer V5.1 (hereafter called WebSphere Studio). The description is also applicable for V5.0.

Transaction isolation level setting for a data source reference

The following steps show how to set the transaction isolation value for the Customer EJB:

  1. Import the EAR file BankCustomerEAR.jar using File -> Import...
  2. Open a J2EE Hierarchy View in a J2EE perspective. In the left panel, expand EJB Modules -> BankCustomerEJB, and then double click on BankCustomerEJB.
  3. Click on the References tab on the bottom of the right panel. A panel appears as shown in Figure 2.
    Figure 2. J2EE hierarchy view for CustomerEJB module
    J2EE hierarchy view for CustomerEJB module
  4. Click on Customer as shown in the Beans list, and then click Add at the bottom of the list to add a data source reference.
  5. In the Add Reference dialog, click on the resource reference to add it. Click Next to advance to the next dialog.
  6. Enter the name, jdbc/myDS. This name is the local JNDI name being looked up in your bean code. This JNDI name is not the JNDI name of the data source in the runtime environment. When you install the application, link the JNDI name of the data source in the runtime environment to this data source reference. At installation time, it is bound to the data source with the JNDI name jdbc/CustomerDS in the runtime environment.
  7. Select javax.sql.DataSource as the Type because the Customer BMP EJB accesses a relational database backend.
  8. In the Authentication field, you can select either Container or Application as the resource authentication type. In this example, select the Container as the authentication type. The resource authentication for the Account CMP is set to "Per_Container", which corresponds to "Container" (see Database authentication in WebSphere Application Server V5). If you set this field to "Application", connections are not shared between Customer EJB and Account EJB because res-auth values do not match.
  9. Keep Shareable as the value for the sharing scope. If you select Unshareable, your application does not share connections with other applications.
  10. Click Finish.
    Figure 3. Setting data source reference's transaction isolation level
    Setting data source reference€™s transaction isolation level
  11. Expand Customer in the References list. You see the right panel of WebSphere Studio as shown in Figure 3. In the References list, there is a ResourceRef jdbc/myDS under the Customer EJB. To the right side of the list, you can see the Sharing scope field has a value of Shareable.
  12. Under the WebSphere Bindings section, enter jdbc/CustomerDS as the JNDI name. This JNDI name is the data source JNDI name in the runtime environment.
  13. For the working case, select TRANSACTION_REPEATABLE_READ from the isolation level drop down list. Any connections acquired from this data source will have a transaction isolation level set to REPEATABLE_READ. Otherwise, select TRANSACTION_SERIALIZABLE from the list for the deadlock case. Figure 3 shows the transaction isolation level that causes the deadlock.
  14. Save the deployment descriptor.

    If you click the Source tab, which corresponds to the file META-INF/ejb-jar.xml file in the EJB Jar file, you can see the following <resource-ref> section under entity EJB Customer as shown in the Listing 5.

Listing 5. <resource-ref> section in ejb-jar.xml
<entity id="Customer">
... ...
	<resource-ref id="ResourceRef_1078633874297">
		<description></description>
		<res-ref-name>jdbc/myDS</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
		<res-sharing-scope>Shareable</res-sharing-scope>
	</resource-ref>

If you switch to the Project Navigator view, and open file BankCustomerEJB/ejbModule/META-INF/ibm-ejb-jar-ext.xmi, you see the following <resourceRefExtensions> section as shown in the Listing 6. You can see the isolation level is set to SERIALIZABLE.

Listing 6. <resourceRefExtensions> section in META-INF/ibm-ejb-jar-ext.xmi
<ejbExtensions xmi:type="ejbext:EntityExtension" xmi:id="EntityExtension_1067213629996"> 
    <enterpriseBean xmi:type="ejb:Entity" href="META-INF/ejb-jar.xml#Customer"/>
    <resourceRefExtensions xmi:id="ResourceRefExtension_1078633874417" 
        isolationLevel="TRANSACTION_SERIALIZABLE">
      <resourceRef href="META-INF/ejb-jar.xml#ResourceRef_1078633874297"/>
    </resourceRefExtensions>
  </ejbExtensions>

You have successfully created a data source reference called jdbc/myDS for the Customer BMP EJB and set the transaction isolation level of this data source reference to TRANSACTION_SERIALIZABLE.

Access intent setting for Account CMP EJB

As described in Application example, the Account CMP EJB has its access intent set to wsPessimisticUpdate. The following steps show how to set the access intent for a CMP EJB:

  1. Click the Access tab on bottom of the right panel.
  2. In the list of Default Access Intent for Entities 2.x (Bean Level), you see two EJBs: Account and Customer. Click Account EJB in the list, and click the Add button to the right of the list.
    Figure 4. Setting access intent to Account CMP EJB
    Setting access intent to Account CMP EJB
  3. An Add Access Intent dialog appears as shown in Figure 4. You can select wsPessimisticUpdate from the dropdown list and click Finish.
  4. Save the deployment descriptor.

    If you switch to the Project Navigator view, and open file BankCustomerEJB/ejbModule/META-INF/ibm-ejb-jar-bnd.xmi, you see the following <appliedAccessIntents> section as shown in the Listing 7. You can see the access intent name is wsPessimisticUpdate.

Listing 7. <appliedAccessIntents> section in META-INF/ibm-ejb-jar-bnd.xmi
<appliedAccessIntents xmi:id="AppliedAccessIntent_1078634268363" 
    name="com.ibm.websphere.ejbquery.Default" description="" accessIntentName="wsPessimisticUpdate">
    <methodElements xmi:id="MethodElement_1078634268363" type="Unspecified">
      <enterpriseBean xmi:type="ejb:ContainerManagedEntity" href="META-INF/ejb-jar.xml#Account"/>
    </methodElements>
  </appliedAccessIntents>

You have successfully set the Account CMP EJB's access intent to wsPessimisticUpdate. This access intent is used by all methods of the Account CMP EJB because you set it at the bean level.

You can install the BankCustomerEAR application and see how the access intent and isolation level affect connection sharing. For more detail, see the readme.txt in the BankCustomerEAR.ear file. When you run the BankCustomer application, you receive a deadlock exception. Follow the steps in Transaction isolation level setting for a data source reference to change the transaction isolation level to REPEATABLE_READ, and run the application again. The application should work successfully.

Conclusion

This article focuses on how to share the connections in J2EE applications by presenting different programming models and examples. Sharing connections can reduce the size of the connection pool and avoid deadlocks. However, there are disadvantages of sharing connections. For example, you cannot change the connection attributes of shared connections in your applications. You need to decide whether or not to share connections based on how you implement your applications.


Download

DescriptionNameSize
Code sampleBankCustomerEAR.ear  ( HTTP | FTP )18KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

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.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=16145
ArticleTitle=Sharing connections in WebSphere Application Server V5
publish-date=04142004