Oracle GlassFish Server 3.0.1 Application Development Guide

Chapter 9 Using Enterprise JavaBeans Technology

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

For general information about enterprise beans, see Part IV, Enterprise Beans, in The Java EE 6 Tutorial.


Note –

The Web Profile of the GlassFish Server supports the EJB 3.1 Lite specification, which allows enterprise beans within web applications, among other features. The full GlassFish Server supports the entire EJB 3.1 specification. For details, see JSR 318.

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


Value Added Features

The GlassFish 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 GlassFish 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 GlassFish 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 GlassFish 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 Oracle GlassFish Server 3.0.1 Application Deployment Guide.

Pooling and Caching

The EJB container of the GlassFish 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 GlassFish 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 Oracle GlassFish Server 3.0.1 Application Deployment Guide.

Pooling Parameters

One of the most important parameters of GlassFish 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

GlassFish 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 GlassFish 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 Oracle GlassFish Server 3.0.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.

The EJB Timer Service in GlassFish Server is preconfigured to use an embedded version of the Java DB database.

The timer service is automatically enabled when you deploy an application or module that uses it.

You can verify that the timer service is running by accessing the following URL:


http://localhost:8080/ejb-timer-service-app/timer

The EJB Timer Service configuration can store persistent timer information in any database supported by the GlassFish Server for persistence. For a list of the JDBC drivers currently supported by the GlassFish Server, see the Oracle GlassFish Server 3.0.1 Release Notes. For configurations of supported and other drivers, see Configuration Specifics for JDBC Drivers in Oracle GlassFish Server 3.0.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. If the EJB Timer Service has already been started, you must also create the timer database table. DDL files are located in as-install/lib/install/databases.

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 the asadmin list-timers command, see the Oracle GlassFish Server 3.0.1 Reference Manual.

Using Session Beans

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

Information on session beans is contained in the Enterprise JavaBeans Specification, v3.1.

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 GlassFish 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 Oracle GlassFish Server 3.0.1 Application Deployment Guide.

The GlassFish 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 Oracle GlassFish Server 3.0.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 Oracle GlassFish Server 3.0.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.

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 GlassFish 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 GlassFish 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 -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 https://glassfish.dev.java.net/nonav/docs/v3/api/ 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 Oracle GlassFish Server 3.0.1 Application Deployment Guide.

Using Message-Driven Beans

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

Message-Driven Bean Configuration

This section addresses the following configuration topics:

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 GlassFish 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 Oracle GlassFish Server 3.0.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 Administration Console. The Monitor tab is accessible from the Application Server page.


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 8, Administering the Monitoring Service, in Oracle GlassFish Server 3.0.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 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 8, Administering the Monitoring Service, in Oracle GlassFish Server 3.0.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 GlassFish 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. Here is an example asadmin set command that sets this property:


asadmin set server-config.mdb-container.property.cmt-max-runtime-exceptions="5"

For more information about the asadmin set command, see the Oracle GlassFish Server 3.0.1 Reference Manual.

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 is deprecated.


Handling Transactions With Enterprise Beans

This section describes the transaction support built into the Enterprise JavaBeans programming model for the GlassFish 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 GlassFish 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 GlassFish 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 Administration Console and click the Help button. Also see Chapter 21, Administering Transactions, in Oracle GlassFish Server 3.0.1 Administration Guide.