Sun Java logo     Previous      Contents      Index      Next     

Sun logo
Sun Java System Application Server Platform Edition 8 Developer's Guide 

Chapter 7
Using Enterprise JavaBeans Technology

This section provides an overview of how the Java™ 2 Platform, Enterprise Edition (J2EE™ platform) Enterprise JavaBeans™ (EJB™) technology works in the application programming model of the Sun Java™ System Application Server environment. This section addresses the following topics:


Summary of EJB 2.1 Changes

Sun Java System Application Server supports the Sun Microsystems Enterprise JavaBeans (EJB) architecture as defined by the Enterprise JavaBeans Specification, v2.1 and is compliant with the Enterprise JavaBeans Specification, v2.0.


Note

You can deploy existing 2.0 beans in the Sun Java System Application Server, but new beans should be developed as 2.1 enterprise beans.


The changes in the Enterprise JavaBeans Specification, v2.1 that impact enterprise beans in the Sun Java System Application Server environment are as follows:


Value Added Features

The Sun Java System Application 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 Sun Java System Application Server provides is the read-only bean, an entity bean that is never modified by an EJB client. Read-only beans avoid database updates completely. A read-only bean must use bean-managed persistence and is not portable.

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 Sun Java System Application 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 in the ejb-jar.xml file, it is easy to configure a read-only bean that is (a) always refreshed, (b) periodically refreshed, (c) never refreshed, or (d) programmatically refreshed.

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.

pass-by-reference

The pass-by-reference element in the sun-ejb-jar.xml file allows you to specify the parameter passing semantics for co-located remote EJB invocations. This is an opportunity to improve performance. Use of this feature can result in non-portable applications. See “pass-by-reference” on page 195.

Pooling and Caching

The EJB container of the Sun Java System Application 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 the method calls of the home interface. 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 can be controlled using pool-related properties in the domain.xml and sun-ejb-jar.xml files.

In addition, the Sun Java System Application Server supports a number of tunable parameters that can be used to 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 will 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 domain.xml and sun-ejb-jar.xml files.

Pooling and caching parameters for the sun-ejb-jar.xml file are discussed in “Pooling and Caching Elements” on page 215.

Pooling Parameters

One of the most important parameters of Sun Java System Application 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 there is always this many beans 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, through 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/destroys any bean instance that is idle for this specified duration.

Caching Parameters

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

The Sun Java System Application 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 be configured to passivate beans that were idle (not accessed for a specified duration) to be passivated.

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.

You can override this timeout for an individual bean using 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.


EJB Timer Service

The EJB Timer Service uses a database to store persistent information about EJB timers. By default, the EJB Timer Service in Sun Java System Application Server is preconfigured to use an embedded version of PointBase. You can change the EJB Timer Service configuration to store persistent timer information in any database supported by the Sun Java System Application Server CMP container. See “Configurations for Specific JDBC Drivers” on page 364.

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 for PointBase (ejbtimer_pointbase.sql) and Oracle (ejbtimer_oracle.sql) are located in install_dir/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.


Using Session Beans

This section provides guidelines for creating session beans in the Sun Java System Application Server 8 environment. This section addresses the following topics:

Extensive information on session beans is contained in the chapters 6, 7, and 8 of the Enterprise JavaBeans Specification, v2.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 transaction managed by the container.

A container managing stateless session beans has a different charter from a container managing stateful session beans.

Stateless Container

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

A stateless session bean container uses a bean pool to service requests. The Sun Java System Application 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” on page 184.

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 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 can be 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 domain.xml file using the configuration APIs.

For more information about sun-ejb-jar.xml, see “The sun-ejb-jar.xml File” on page 184.

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.

Restrictions and Optimizations

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

Optimizing Session Bean Performance

For stateful session beans, co-locating the stateful beans with their clients so that the client and bean are executing in the same process address space will improve performance.

Restricting Transactions

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


Using Read-Only Beans

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


Note

For this release of Sun Java System Application Server, only entity beans that use bean-managed persistence can be designated as read-only.

Read-only beans are specific to Sun Java System Application Server and are not part of the Enterprise JavaBeans Specification, v2.1. Use of this feature results in a non-portable application.


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 may 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 will be 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

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 will invoke ejbLoad.

Refreshing Periodically

Read-only beans can be refreshed periodically by specifying the refresh-period-in-seconds element in the sun-ejb-jar.xml file.

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. You can 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 user can look 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.

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 Java System Application Server-specific XML file, the is-read-only-bean element must be set to true. That is:

Also, the refresh-period-in-seconds element in the sun-ejb-jar.xml file may 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 with the same transaction context are routed to the same read-only bean instance. The deployer can specify if such multiple requests have to be serialized by setting 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 Java System Application Server Reference.


Using Message-Driven Beans

This section describes message-driven beans and explains the requirements for creating them in the Sun Java System Application Server 8 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 1.5 inbound resource adapter. The message-driven bean container uses the JMS service integrated into the Sun Java System Application 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.xmlfile for a message-driven bean can be used to specify the connection factory used by the container to create the container connection to the JMS provider.

If the mdb-connection-factory element is not specified, a default one created at server startup is used. This provides connection to the built-in Sun Java System Message Queue broker on the port that is specified in the jms-service element (if enabled) in the domain.xml file, using the default user name/password (resource principal) of the Sun Java System Message Queue. Refer to the Sun Java System Message Queue Developer’s Guide for more information.

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” on page 184.

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, see the Sun Java System Application Server Administration Console online help and Administration Guide.


Note

Running monitoring when it is not need may impact performance, so you may choose to turn monitoring off using the asadmin command or the Administration Console when it is not in use.


Automatic Reconnection to JMS Provider

When the Sun Java System Application Server is started, for each deployed message-driven bean that is a JMS client, its container keeps a connection to the JMS provider. When the connection is broken, the container is not able to receive messages from the JMS provider and, therefore, is unable to deliver messages to its message-driven bean instances. When the auto reconnection feature is enabled, the container automatically tries to reconnect to the JMS provider if the connection is broken.

The mdb-container element in the domain.xml file contains auto reconnection properties. By default, reconnect-enabled is set to false and reconnect-delay-in-seconds is set to 60 seconds. That is, there is a delay of 60 seconds before each attempt to reconnect, and reconnect-max-retries is set to 60.

The container logs messages for each reconnect attempt.


Note

Depending on where the message processing stage is, if the connection is broken, the onMessage method may not be able to complete successfully, or the transaction may be rolled back due to a JMS exception. When the container reestablishes connection to the JMS provider, JMS message redelivery semantics apply.


Refer to the Sun Java System Application Server Reference for information on auto reconnect properties of the mdb-container element in the domain.xml file.

Restrictions and Optimizations

This section discusses the following restrictions and performance optimizations that you should be aware of in 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 will impact performance and server resources.

When configuring message-driven bean pool properties, you must 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 may access.

Performance and resource usage tuning should also consider potential JMS provider properties for the connection factory that is used by the container (mdb-connection-factory element in deployment descriptor). For example, the Sun Java System Message Queue flow control related properties for connection factory should be tuned in situations where the message incoming rate is much higher than max-pool-size can handle.

Refer to the Sun Java System Application Server Administration Guide for information on how to get message-driven bean pool statistics.

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, v2.1 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 Sun Java System Application 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. This default container behavior can be changed using 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 may be deprecated in the future.


Sample Message-Driven Bean XML Files

This section includes the following sample files:

For general information on the sun-ejb-jar.xml file, see “The sun-ejb-jar.xml File” on page 184.

Sample ejb-jar.xml File

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
  <enterprise-beans>
    <message-driven>
      <ejb-name>MessageBean</ejb-name>
      <ejb-class>samples.mdb.ejb.MessageBean</ejb-class>
      <transaction-type>Container</transaction-type>
      <message-driven-destination>
        <destination-type>javax.jms.Queue</destination-type>
      </message-driven-destination>
      <resource-ref>
        <res-ref-name>jms/QueueConnectionFactory</res-ref-name>
        <res-type>javax.jms.QueueConnectionFactory</res-type>
        <res-auth>Container</res-auth>
      </resource-ref>
    </message-driven>
  </enterprise-beans>
    <assembly-descriptor>
      <container-transaction>
        <method>
          <ejb-name>MessageBean</ejb-name>
          <method-intf>Bean</method-intf>
          <method-name>onMessage</method-name>
          <method-params>
            <method-param>javax.jms.Message</method-param>
          </method-params>
        </method>
      <trans-attribute>NotSupported</trans-attribute>
    </container-transaction>
  </assembly-descriptor
</ejb-jar>

Sample sun-ejb-jar.xml File

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sun-ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Application Server 8.0 EJB 2.1//EN' 'http://www.sun.com/software/appserver/dtds/sun-ejb-jar_2_1-0.dtd'>

<sun-ejb-jar>
  <enterprise-beans>
    <ejb>
      <ejb-name>MessageBean</ejb-name>
      <jndi-name>jms/sample/Queue</jndi-name>
      <resource-ref>
        <res-ref-name>jms/QueueConnectionFactory</res-ref-name>
        <jndi-name>jms/sample/QueueConnectionFactory</jndi-name>
        <default-resource-principal>
          <name>guest</name>
          <password>guest</password>
        </default-resource-principal>
      </resource-ref>
      <mdb-connection-factory>
        <jndi-name>jms/sample/QueueConnectionFactory</jndi-name>
        <default-resource-principal>
          <name>guest</name>
          <password>guest</password>
        </default-resource-principal>
      </mdb-connection-factory>
    </ejb>
  </enterprise-beans>
</sun-ejb-jar>


Handling Transactions with Enterprise Beans

This section describes the transaction support built into the Enterprise JavaBeans (EJBs) programming model for Sun Java System Application Server 8.

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

Flat Transactions

The Enterprise JavaBeans Specification, v2.1 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. You cannot start another transaction 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 Sun Java System Application 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 “Naming Environment for J2EE Application Components” on page 388.

Commit Options

The EBJ 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 Sun Java System Application 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, see the Sun Java System Application Server Administration Console online help and the Sun Java System Application Server Administration Guide.



Previous      Contents      Index      Next     


Copyright 2004 Sun Microsystems, Inc. All rights reserved.