Sun GlassFish Enterprise Server 2.1 Developer's Guide

Chapter 9 Using Enterprise JavaBeans Technology

This chapter describes how Enterprise JavaBeansTM (EJBTM) technology is supported in the Sun GlassFish Enterprise Server. This chapter addresses the following topics:

For general information about enterprise beans, see “Part Three: Enterprise Beans” in the Java EE 5 Tutorial.

Summary of EJB 3.0 Changes

The Enterprise Server supports and is compliant with the Sun Microsystems Enterprise JavaBeans (EJB) architecture as defined by the Enterprise JavaBeans Specification, v3.0, also known as JSR 220.


Note –

The Enterprise Server is backward compatible with 1.1, 2.0, and 2.1 enterprise beans. However, to take advantage of version 3.0 features, you should develop new beans as 3.0 enterprise beans.


The main changes in the Enterprise JavaBeans Specification, v3.0 that impact enterprise beans in the Enterprise Server environment are as follows:

Value Added Features

The Enterprise Server provides a number of value additions that relate to EJB development. These capabilities are discussed in the following sections. References to more in-depth material are included.

Read-Only Beans

Another feature that the Enterprise Server provides is the read-only bean, an EJB 2.1 entity bean that is never modified by an EJB client. Read-only beans avoid database updates completely.


Note –

Read-only beans are specific to the Enterprise Server and are not part of the Enterprise JavaBeans Specification, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable application.

To make an EJB 3.0 entity read-only, use @Column annotations to mark its columns insertable=false and updatable=false.


A read-only bean can be used to cache a database entry that is frequently accessed but rarely updated (externally by other beans). When the data that is cached by a read-only bean is updated by another bean, the read-only bean can be notified to refresh its cached data.

The Enterprise Server provides a number of ways by which a read-only bean’s state can be refreshed. By setting the refresh-period-in-seconds element in the sun-ejb-jar.xml file and the trans-attribute element (or @TransactionAttribute annotation) in the ejb-jar.xml file, it is easy to configure a read-only bean that is one of the following:

Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. For further information and usage guidelines, see Using Read-Only Beans.

The pass-by-reference Element

The pass-by-reference element in the sun-ejb-jar.xml file allows you to specify the parameter passing semantics for colocated remote EJB invocations. This is an opportunity to improve performance. However, use of this feature results in non-portable applications. See pass-by-reference in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

Pooling and Caching

The EJB container of the Enterprise Server pools anonymous instances (message-driven beans, stateless session beans, and entity beans) to reduce the overhead of creating and destroying objects. The EJB container maintains the free pool for each bean that is deployed. Bean instances in the free pool have no identity (that is, no primary key associated) and are used to serve method calls. The free beans are also used to serve all methods for stateless session beans.

Bean instances in the free pool transition from a Pooled state to a Cached state after ejbCreate and the business methods run. The size and behavior of each pool is controlled using pool-related properties in the EJB container or the sun-ejb-jar.xml file.

In addition, the Enterprise Server supports a number of tunable parameters that can control the number of “stateful” instances (stateful session beans and entity beans) cached as well as the duration they are cached. Multiple bean instances that refer to the same database row in a table can be cached. The EJB container maintains a cache for each bean that is deployed.

To achieve scalability, the container selectively evicts some bean instances from the cache, usually when cache overflows. These evicted bean instances return to the free bean pool. The size and behavior of each cache can be controlled using the cache-related properties in the EJB container or the sun-ejb-jar.xml file.

Pooling and caching parameters for the sun-ejb-jar.xml file are described in bean-cache in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

Pooling Parameters

One of the most important parameters of Enterprise Server pooling is steady-pool-size. When steady-pool-size is set to greater than 0, the container not only pre-populates the bean pool with the specified number of beans, but also attempts to ensure that this number of beans is always available in the free pool. This ensures that there are enough beans in the ready to serve state to process user requests.

This parameter does not necessarily guarantee that no more than steady-pool-size instances exist at a given time. It only governs the number of instances that are pooled over a long period of time. For example, suppose an idle stateless session container has a fully-populated pool with a steady-pool-size of 10. If 20 concurrent requests arrive for the EJB component, the container creates 10 additional instances to satisfy the burst of requests. The advantage of this is that it prevents the container from blocking any of the incoming requests. However, if the activity dies down to 10 or fewer concurrent requests, the additional 10 instances are discarded.

Another parameter, pool-idle-timeout-in-seconds, allows the administrator to specify the amount of time a bean instance can be idle in the pool. When pool-idle-timeout-in-seconds is set to greater than 0, the container removes or destroys any bean instance that is idle for this specified duration.

Caching Parameters

Enterprise Server provides a way that completely avoids caching of entity beans, using commit option C. Commit option C is particularly useful if beans are accessed in large number but very rarely reused. For additional information, refer to Commit Options.

The Enterprise Server caches can be either bounded or unbounded. Bounded caches have limits on the number of beans that they can hold beyond which beans are passivated. For stateful session beans, there are three ways (LRU, NRU and FIFO) of picking victim beans when cache overflow occurs. Caches can also passivate beans that are idle (not accessed for a specified duration).

Bean-Level Container-Managed Transaction Timeouts

The default transaction timeout for the domain is specified using the Transaction Timeout setting of the Transaction Service. A transaction started by the container must commit (or rollback) within this time, regardless of whether the transaction is suspended (and resumed), or the transaction is marked for rollback.

To override this timeout for an individual bean, use the optional cmt-timeout-in-seconds element in sun-ejb-jar.xml. The default value, 0, specifies that the default Transaction Service timeout is used. The value of cmt-timeout-in-seconds is used for all methods in the bean that start a new container-managed transaction. This value is not used if the bean joins a client transaction.

Priority Based Scheduling of Remote Bean Invocations

You can create multiple thread pools, each having its own work queues. An optional element in the sun-ejb-jar.xml file, use-thread-pool-id, specifies the thread pool that processes the requests for the bean. The bean must have a remote interface, or use-thread-pool-id is ignored. You can create different thread pools and specify the appropriate thread pool ID for a bean that requires a quick response time. If there is no such thread pool configured or if the element is absent, the default thread pool is used.

Immediate Flushing

Normally, all entity bean updates within a transaction are batched and executed at the end of the transaction. The only exception is the database flush that precedes execution of a finder or select query.

Since a transaction often spans many method calls, you might want to find out if the updates made by a method succeeded or failed immediately after method execution. To force a flush at the end of a method’s execution, use the flush-at-end-of-method element in the sun-ejb-jar.xml file. Only non-finder methods in an entity bean can be flush-enabled. (For an EJB 2.1 bean, these methods must be in the Local, Local Home, Remote, or Remote Home interface.) See flush-at-end-of-method in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

Upon completion of the method, the EJB container updates the database. Any exception thrown by the underlying data store is wrapped as follows:

All normal end-of-transaction database synchronization steps occur regardless of whether the database has been flushed during the transaction.

EJB Timer Service

The EJB Timer Service uses a database to store persistent information about EJB timers. In the developer profile, the EJB Timer Service in Enterprise Server is preconfigured to use an embedded version of the Java DB database. The EJB Timer Service configuration can store persistent timer information in any database supported by the Enterprise Server for persistence.

For a list of the JDBC drivers currently supported by the Enterprise Server, see the Sun GlassFish Enterprise Server 2.1 Release Notes. For configurations of supported and other drivers, see Configurations for Specific JDBC Drivers in Sun GlassFish Enterprise Server 2.1 Administration Guide.

To change the database used by the EJB Timer Service, set the EJB Timer Service’s Timer DataSource setting to a valid JDBC resource. You must also create the timer database table. DDL files are located in as-install/lib/install/databases. Ideally, each cluster should have its own timer table.

Using the EJB Timer Service is equivalent to interacting with a single JDBC resource manager. If an EJB component or application accesses a database either directly through JDBC or indirectly (for example, through an entity bean’s persistence mechanism), and also interacts with the EJB Timer Service, its data source must be configured with an XA JDBC driver.

You can change the following EJB Timer Service settings. You must restart the server for the changes to take effect.

For information about configuring EJB Timer Service settings, see Chapter 8, SIP, Web, and EJB Containers, in Sun GlassFish Enterprise Server 2.1 Administration Guide. For information about the asadmin list-timers and asadmin migrate-timers commands, see the Sun GlassFish Enterprise Server 2.1 Reference Manual.

Using Session Beans

This section provides guidelines for creating session beans in the Enterprise Server environment. This section addresses the following topics:

Extensive information on session beans is contained in Chapters 3 and 4 of the Enterprise JavaBeans Specification, v3.0, EJB Core Contracts and Requirements.

About the Session Bean Containers

Like an entity bean, a session bean can access a database through Java Database Connectivity (JDBC) calls. A session bean can also provide transaction settings. These transaction settings and JDBC calls are referenced by the session bean’s container, allowing it to participate in transactions managed by the container.

A container managing stateless session beans has a different charter from a container managing stateful session beans. This section addresses the following topics:

Stateless Container

The stateless container manages stateless session beans, which, by definition, do not carry client-specific states. All session beans (of a particular type) are considered equal.

A stateless session bean container uses a bean pool to service requests. The Enterprise Server specific deployment descriptor file, sun-ejb-jar.xml, contains the properties that define the pool:

For more information about sun-ejb-jar.xml, see The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

The Enterprise Server provides the wscompile and wsdeploy tools to help you implement a web service endpoint as a stateless session bean. For more information about these tools, see the Sun GlassFish Enterprise Server 2.1 Reference Manual.

Stateful Container

The stateful container manages the stateful session beans, which, by definition, carry the client-specific state. There is a one-to-one relationship between the client and the stateful session beans. At creation, each stateful session bean (SFSB) is given a unique session ID that is used to access the session bean so that an instance of a stateful session bean is accessed by a single client only.

Stateful session beans are managed using cache. The size and behavior of stateful session beans cache are controlled by specifying the following sun-ejb-jar.xml parameters:

The max-cache-size element specifies the maximum number of session beans that are held in cache. If the cache overflows (when the number of beans exceeds max-cache-size), the container then passivates some beans or writes out the serialized state of the bean into a file. The directory in which the file is created is obtained from the EJB container using the configuration APIs.

For more information about sun-ejb-jar.xml, see The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

The passivated beans are stored on the file system. The Session Store Location setting in the EJB container allows the administrator to specify the directory where passivated beans are stored. By default, passivated stateful session beans are stored in application-specific subdirectories created under domain-dir/session-store.


Note –

Make sure the delete option is set in the server.policy file, or expired file-based sessions might not be deleted properly. For more information about server.policy, see The server.policy File.


The Session Store Location setting also determines where the session state is persisted if it is not highly available; see Choosing a Persistence Store.

Stateful Session Bean Failover

An SFSB’s state can be saved in a persistent store in case a server instance fails. The state of an SFSB is saved to the persistent store at predefined points in its life cycle. This is called checkpointing. If SFSB checkpointing is enabled, checkpointing generally occurs after any transaction involving the SFSB is completed, even if the transaction rolls back.

However, if an SFSB participates in a bean-managed transaction, the transaction might be committed in the middle of the execution of a bean method. Since the bean’s state might be undergoing transition as a result of the method invocation, this is not an appropriate instant to checkpoint the bean’s state. In this case, the EJB container checkpoints the bean’s state at the end of the corresponding method, provided the bean is not in the scope of another transaction when that method ends. If a bean-managed transaction spans across multiple methods, checkpointing is delayed until there is no active transaction at the end of a subsequent method.

The state of an SFSB is not necessarily transactional and might be significantly modified as a result of non-transactional business methods. If this is the case for an SFSB, you can specify a list of checkpointed methods. If SFSB checkpointing is enabled, checkpointing occurs after any checkpointed methods are completed.


Note –

Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server 2.1 Administration Guide.


The following table lists the types of references that SFSB failover supports. All objects bound into an SFSB must be one of the supported types. In the table, No indicates that failover for the object type might not work in all cases and that no failover support is provided. However, failover might work in some cases for that object type. For example, failover might work because the class implementing that type is serializable.

Table 9–1 Object Types Supported for Java EE Stateful Session Bean State Failover

Java Object Type 

Failover Support 

Colocated or distributed stateless session, stateful session, or entity bean reference 

Yes 

JNDI context 

Yes, InitialContext and java:comp/env

UserTransaction 

Yes, but if the instance that fails is never restarted, any prepared global transactions are lost and might not be correctly rolled back or committed. 

JDBC DataSource 

No 

Java Message Service (JMS) ConnectionFactory, Destination 

No 

JavaMail Session 

No 

Connection Factory 

No 

Administered Object 

No 

Web service reference 

No 

Serializable Java types 

Yes 

Extended persistence context 

No 

For more information about the InitialContext, see Accessing the Naming Context. For more information about transaction recovery, see Chapter 16, Using the Transaction Service. For more information about Administered Objects, see Creating Physical Destinations.


Note –

Idempotent URLs are supported along the HTTP path, but not the RMI-IIOP path. For more information, see Configuring Idempotent URL Requests.

If a server instance to which an RMI-IIOP client request is sent crashes during the request processing (before the response is prepared and sent back to the client), an error is sent to the client. The client must retry the request explicitly. When the client retries the request, the request is sent to another server instance in the cluster, which retrieves session state information for this client.

HTTP sessions can also be saved in a persistent store in case a server instance fails. In addition, if a distributable web application references an SFSB, and the web application’s session fails over, the EJB reference is also failed over. For more information, see Distributed Sessions and Persistence.

If an SFSB that uses session persistence is undeployed while the Enterprise Server instance is stopped, the session data in the persistence store might not be cleared. To prevent this, undeploy the SFSB while the Enterprise Server instance is running.


Configure SFSB failover by:

Choosing a Persistence Store

The following types of persistent storage are supported for passivation and checkpointing of the SFSB state:

Choose the persistence store in one of the following ways:

For more information, see the Sun GlassFish Enterprise Server 2.1 High Availability Administration Guide.

Enabling Checkpointing

The following sections describe how to enable SFSB checkpointing:

Server Instance and EJB Container Levels

To enable SFSB checkpointing at the server instance or EJB container level, see Choosing a Persistence Store.

Application and EJB Module Levels

To enable SFSB checkpointing at the application or EJB module level during deployment, use the asadmin deploy or asadmin deploydir command with the --availabilityenabled option set to true. For details, see the Sun GlassFish Enterprise Server 2.1 Reference Manual.

SFSB Level

To enable SFSB checkpointing at the SFSB level, set availability-enabled="true" in the ejb element of the SFSB’s sun-ejb-jar.xml file as follows:

<sun-ejb-jar>
   ...
   <enterprise-beans>
      ...
      <ejb availability-enabled="true">
         <ejb-name>MySFSB</ejb-name>
      </ejb>
   ...
   </enterprise-beans>
</sun-ejb-jar>

Specifying Methods to Be Checkpointed

If SFSB checkpointing is enabled, checkpointing generally occurs after any transaction involving the SFSB is completed, even if the transaction rolls back.

To specify additional optional checkpointing of SFSBs at the end of non-transactional business methods that cause important modifications to the bean’s state, use the checkpoint-at-end-of-method element within the ejb element in sun-ejb-jar.xml.

For example:

<sun-ejb-jar>
   ...
   <enterprise-beans>
      ...
      <ejb availability-enabled="true">
         <ejb-name>ShoppingCartEJB</ejb-name>
         <checkpoint-at-end-of-method>
            <method>
               <method-name>addToCart</method-name>
            </method>
         </checkpoint-at-end-of-method>
      </ejb>
      ...
   </enterprise-beans>
</sun-ejb-jar>

For details, see checkpoint-at-end-of-method in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

The non-transactional methods in the checkpoint-at-end-of-method element can be the following:

Any other methods mentioned in this list are ignored. At the end of invocation of each of these methods, the EJB container saves the state of the SFSB to persistent store.


Note –

If an SFSB does not participate in any transaction, and if none of its methods are explicitly specified in the checkpoint-at-end-of-method element, the bean’s state is not checkpointed at all even if availability-enabled="true" for this bean.

For better performance, specify a small subset of methods. The methods chosen should accomplish a significant amount of work in the context of the Java EE application or should result in some important modification to the bean’s state.


Session Bean Restrictions and Optimizations

This section discusses restrictions on developing session beans and provides some optimization guidelines:

Optimizing Session Bean Performance

For stateful session beans, colocating the stateful beans with their clients so that the client and bean are executing in the same process address space improves performance.

Restricting Transactions

The following restrictions on transactions are enforced by the container and must be observed as session beans are developed:

Using Read-Only Beans

A read-only bean is an EJB 2.1 entity bean that is never modified by an EJB client. The data that a read-only bean represents can be updated externally by other enterprise beans, or by other means, such as direct database updates.


Note –

Read-only beans are specific to the Enterprise Server and are not part of the Enterprise JavaBeans Specification, v2.1. Use of this feature for an EJB 2.1 bean results in a non-portable application.

To make an EJB 3.0 entity bean read-only, use @Column annotations to mark its columns insertable=false and updatable=false.


Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. The following topics are addressed in this section:

Read-Only Bean Characteristics and Life Cycle

Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. For example, a read-only bean can be used to represent a stock quote for a particular company, which is updated externally. In such a case, using a regular entity bean might incur the burden of calling ejbStore, which can be avoided by using a read-only bean.

Read-only beans have the following characteristics:

A read-only bean comes into existence using the appropriate find methods.

Read-only beans are cached and have the same cache properties as entity beans. When a read-only bean is selected as a victim to make room in the cache, ejbPassivate is called and the bean is returned to the free pool. When in the free pool, the bean has no identity and is used only to serve any finder requests.

Read-only beans are bound to the naming service like regular read-write entity beans, and clients can look up read-only beans the same way read-write entity beans are looked up.

Read-Only Bean Good Practices

For best results, follow these guidelines when developing read-only beans:

Refreshing Read-Only Beans

There are several ways of refreshing read-only beans as addressed in the following sections:

Invoking a Transactional Method

Invoking any transactional method invokes ejbLoad.

Refreshing Periodically

Use the refresh-period-in-seconds element in the sun-ejb-jar.xml file to refresh a read-only bean periodically.


Note –

This is the only way to refresh the bean state if the data can be modified external to the Enterprise Server.


By default, a single timer is used for all instances of a read-only bean. When that timer fires, all bean instances are marked as expired and are refreshed from the database the next time they are used.

Use the -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true flag to refresh each bean instance independently upon access if its refresh period has expired. The default is false. Note that each instance still has the same refresh period. This additional level of granularity can improve the performance of read-only beans that do not need to be refreshed at the same time.

To set this flag, use the asadmin create-jvm-options command. For example:


asadmin create-jvm-options --user adminuser -Dcom.sun.ejb.containers.readonly.relative.refresh.mode=true

Refreshing Programmatically

Typically, beans that update any data that is cached by read-only beans need to notify the read-only beans to refresh their state. Use ReadOnlyBeanNotifier to force the refresh of read-only beans.

To do this, invoke the following methods on the ReadOnlyBeanNotifier bean:

public interface ReadOnlyBeanNotifier extends java.rmi.Remote {
   refresh(Object PrimaryKey) throws RemoteException;
 }

The implementation of the ReadOnlyBeanNotifier interface is provided by the container. The bean looks up ReadOnlyBeanNotifier using a fragment of code such as the following example:

com.sun.appserv.ejb.ReadOnlyBeanHelper helper = 
  new com.sun.appserv.ejb.ReadOnlyBeanHelper();
com.sun.appserv.ejb.ReadOnlyBeanNotifier notifier = 
  helper.getReadOnlyBeanNotifier("java:comp/env/ejb/ReadOnlyCustomer");
notifier.refresh(PrimaryKey);

For a local read-only bean notifier, the lookup has this modification:

helper.getReadOnlyBeanLocalNotifier("java:comp/env/ejb/LocalReadOnlyCustomer");

Beans that update any data that is cached by read-only beans need to call the refresh methods. The next (non-transactional) call to the read-only bean invokes ejbLoad.

For Javadoc tool pages relevant to read-only beans, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.ejb package.

Deploying Read-Only Beans

Read-only beans are deployed in the same manner as other entity beans. However, in the entry for the bean in the sun-ejb-jar.xml file, the is-read-only-bean element must be set to true. That is:

<is-read-only-bean>true</is-read-only-bean>

Also, the refresh-period-in-seconds element in the sun-ejb-jar.xml file can be set to some value that specifies the rate at which the bean is refreshed. If this element is missing, no refresh occurs.

All requests in the same transaction context are routed to the same read-only bean instance. Set the allow-concurrent-access element to either true (to allow concurrent accesses) or false (to serialize concurrent access to the same read-only bean). The default is false.

For further information on these elements, refer to The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

Using Message-Driven Beans

This section describes message-driven beans and explains the requirements for creating them in the Enterprise Server environment. This section contains the following topics:

Message-Driven Bean Configuration

This section addresses the following configuration topics:

For information about setting up load balancing for message-driven beans, see Load-Balanced Message Inflow.

Connection Factory and Destination

A message-driven bean is a client to a Connector inbound resource adapter. The message-driven bean container uses the JMS service integrated into the Enterprise Server for message-driven beans that are JMS clients. JMS clients use JMS Connection Factory- and Destination-administered objects. A JMS Connection Factory administered object is a resource manager Connection Factory object that is used to create connections to the JMS provider.

The mdb-connection-factory element in the sun-ejb-jar.xml file for a message-driven bean specifies the connection factory that creates the container connection to the JMS provider.

The jndi-name element of the ejb element in the sun-ejb-jar.xml file specifies the JNDI name of the administered object for the JMS Queue or Topic destination that is associated with the message-driven bean.

Message-Driven Bean Pool

The container manages a pool of message-driven beans for the concurrent processing of a stream of messages. The sun-ejb-jar.xml file contains the elements that define the pool (that is, the bean-pool element):

For more information about sun-ejb-jar.xml, see The sun-ejb-jar.xml File in Sun GlassFish Enterprise Server 2.1 Application Deployment Guide.

Domain-Level Settings

You can control the following domain-level message-driven bean settings in the EJB container:

For information on monitoring message-driven beans, click the Help button in the Admin Console. In the developer profile, the Monitor tab is accessible from the Application Server page. In the Cluster profile, select the Stand-Alone Instances component, select the instance from the table, and select the Monitor tab.


Note –

Running monitoring when it is not needed might impact performance, so you might choose to turn monitoring off when it is not in use. For details, see Chapter 18, Monitoring Components and Services, in Sun GlassFish Enterprise Server 2.1 Administration Guide.


Message-Driven Bean Restrictions and Optimizations

This section discusses the following restrictions and performance optimizations that pertain to developing message-driven beans:

Pool Tuning and Monitoring

The message-driven bean pool is also a pool of threads, with each message-driven bean instance in the pool associating with a server session, and each server session associating with a thread. Therefore, a large pool size also means a high number of threads, which impacts performance and server resources.

When configuring message-driven bean pool properties, make sure to consider factors such as message arrival rate and pattern, onMessage method processing time, overall server resources (threads, memory, and so on), and any concurrency requirements and limitations from other resources that the message-driven bean accesses.

When tuning performance and resource usage, make sure to consider potential JMS provider properties for the connection factory used by the container (the mdb-connection-factory element in the sun-ejb-jar.xml file). For example, you can tune the Sun GlassFish Message Queue flow control related properties for connection factory in situations where the message incoming rate is much higher than max-pool-size can handle.

Refer to Chapter 18, Monitoring Components and Services, in Sun GlassFish Enterprise Server 2.1 Administration Guide for information on how to get message-driven bean pool statistics.

The onMessage Runtime Exception

Message-driven beans, like other well-behaved MessageListeners, should not, in general, throw runtime exceptions. If a message-driven bean’s onMessage method encounters a system-level exception or error that does not allow the method to successfully complete, the Enterprise JavaBeans Specification, v3.0 provides the following guidelines:

Under container-managed transaction demarcation, upon receiving a runtime exception from a message-driven bean’s onMessage method, the container rolls back the container-started transaction and the message is redelivered. This is because the message delivery itself is part of the container-started transaction. By default, the Enterprise Server container closes the container’s connection to the JMS provider when the first runtime exception is received from a message-driven bean instance’s onMessage method. This avoids potential message redelivery looping and protects server resources if the message-driven bean’s onMessage method continues misbehaving. To change this default container behavior, use the cmt-max-runtime-exceptions property of the mdb-container element in the domain.xml file.

The cmt-max-runtime-exceptions property specifies the maximum number of runtime exceptions allowed from a message-driven bean’s onMessage method before the container starts to close the container’s connection to the message source. By default this value is 1; -1 disables this container protection.

A message-driven bean’s onMessage method can use the javax.jms.Message getJMSRedelivered method to check whether a received message is a redelivered message.


Note –

The cmt-max-runtime-exceptions property might be deprecated in the future.


Handling Transactions With Enterprise Beans

This section describes the transaction support built into the Enterprise JavaBeans programming model for the Enterprise Server.

As a developer, you can write an application that updates data in multiple databases distributed across multiple sites. The site might use EJB servers from different vendors. This section provides overview information on the following topics:

Flat Transactions

The Enterprise JavaBeans Specification, v3.0 requires support for flat (as opposed to nested) transactions. In a flat transaction, each transaction is decoupled from and independent of other transactions in the system. Another transaction cannot start in the same thread until the current transaction ends.

Flat transactions are the most prevalent model and are supported by most commercial database systems. Although nested transactions offer a finer granularity of control over transactions, they are supported by far fewer commercial database systems.

Global and Local Transactions

Understanding the distinction between global and local transactions is crucial in understanding the Enterprise Server support for transactions. See Transaction Scope.

Both local and global transactions are demarcated using the javax.transaction.UserTransaction interface, which the client must use. Local transactions bypass the transaction manager and are faster. For more information, see The Transaction Manager, the Transaction Synchronization Registry, and UserTransaction.

Commit Options

The EJB protocol is designed to give the container the flexibility to select the disposition of the instance state at the time a transaction is committed. This allows the container to best manage caching an entity object’s state and associating an entity object identity with the EJB instances.

There are three commit-time options:

The Enterprise Server deployment descriptor has an element, commit-option, that specifies the commit option to be used. Based on the specified commit option, the appropriate handler is instantiated.

Administration and Monitoring

An administrator can control a number of domain-level Transaction Service settings. For details, see Configuring the Transaction Service.

The Transaction Timeout setting can be overridden by a bean. See Bean-Level Container-Managed Transaction Timeouts.

In addition, the administrator can monitor transactions using statistics from the transaction manager that provide information on such activities as the number of transactions completed, rolled back, or recovered since server startup, and transactions presently being processed.

For information on administering and monitoring transactions, select the Transaction Service component under the relevant configuration in the Admin Console and click the Help button. Also see Chapter 12, Transactions, in Sun GlassFish Enterprise Server 2.1 Administration Guide.