30.3. The EJB Container

An EJB container is the component that manages a particular class of EJB. In JBoss there is one instance of the org.jboss.ejb.Container created for each unique configuration of an EJB that is deployed. The actual object that is instantiated is a subclass of Container and the creation of the container instance is managed by the EJBDeployer MBean.

30.3.1. EJBDeployer MBean

The org.jboss.ejb.EJBDeployer MBean is responsible for the creation of EJB containers. Given an EJB JAR that is ready for deployment, the EJBDeployer will create and initialize the necessary EJB containers, one for each type of EJB. The configurable attributes of the EJBDeployer are:
  • VerifyDeployments: a boolean flag indicating if the EJB verifier should be run. This validates that the EJBs in a deployment unit conform to the EJB 2.1 specification. Setting this to true is useful for ensuring your deployments are valid.
  • VerifierVerbose: A boolean that controls the verbosity of any verification failures/warnings that result from the verification process.
  • StrictVerifier: A boolean that enables/disables strict verification. When strict verification is enable an EJB will deploy only if verifier reports no errors.
  • CallByValue: a boolean flag that indicates call by value semantics should be used by default.
  • ValidateDTDs: a boolean flag that indicates if the ejb-jar.xml and jboss.xml descriptors should be validated against their declared DTDs. Setting this to true is useful for ensuring your deployment descriptors are valid.
  • MetricsEnabled: a boolean flag that controls whether container interceptors marked with an metricsEnabled=true attribute should be included in the configuration. This allows one to define a container interceptor configuration that includes metrics type interceptors that can be toggled on and off.
  • WebServiceName: The JMX ObjectName string of the web service MBean that provides support for the dynamic class loading of EJB classes.
  • TransactionManagerServiceName: The JMX ObjectName string of the JTA transaction manager service. This must have an attribute named TransactionManager that returns that javax.transaction.TransactionManager instance.
The deployer contains two central methods: deploy and undeploy. The deploy method takes a URL, which either points to an EJB JAR, or to a directory whose structure is the same as a valid EJB JAR (which is convenient for development purposes). Once a deployment has been made, it can be undeployed by calling undeploy on the same URL. A call to deploy with an already deployed URL will cause an undeploy, followed by deployment of the URL. JBoss has support for full re-deployment of both implementation and interface classes, and will reload any changed classes. This will allow you to develop and update EJBs without ever stopping a running server.
During the deployment of the EJB JAR the EJBDeployer and its associated classes perform three main functions, verify the EJBs, create a container for each unique EJB, initialize the container with the deployment configuration information. We will talk about each function in the following sections. Verifying EJB deployments

When the VerifyDeployments attribute of the EJBDeployer is true, the deployer performs a verification of EJBs in the deployment. The verification checks that an EJB meets EJB specification compliance. This entails validating that the EJB deployment unit contains the required home and remote, local home and local interfaces. It will also check that the objects appearing in these interfaces are of the proper types and that the required methods are present in the implementation class. This is a useful behavior that is enabled by default since there are a number of steps that an EJB developer and deployer must perform correctly to construct a proper EJB JAR, and it is easy to make a mistake. The verification stage attempts to catch any errors and fail the deployment with an error that indicates what needs to be corrected.
Probably the most problematic aspect of writing EJBs is the fact that there is a disconnection between the bean implementation and its remote and home interfaces, as well as its deployment descriptor configuration. It is easy to have these separate elements get out of sync. One tool that helps eliminate this problem is XDoclet. It allows you to use custom JavaDoc-like tags in the EJB bean implementation class to generate the related bean interfaces, deployment descriptors and related objects. See the XDoclet home page, http://sourceforge.net/projects/xdoclet for additional details. Deploying EJBs Into Containers

The most important role performed by the EJBDeployer is the creation of an EJB container and the deployment of the EJB into the container. The deployment phase consists of iterating over EJBs in an EJB JAR, and extracting the bean classes and their metadata as described by the ejb-jar.xml and jboss.xml deployment descriptors. For each EJB in the EJB JAR, the following steps are performed:
  • Create subclass of org.jboss.ejb.Container depending on the type of the EJB: stateless, stateful, BMP entity, CMP entity, or message driven. The container is assigned a unique ClassLoader from which it can load local resources. The uniqueness of the ClassLoader is also used to isolate the standard java:comp JNDI namespace from other J2EE components.
  • Set all container configurable attributes from a merge of the jboss.xml and standardjboss.xml descriptors.
  • Create and add the container interceptors as configured for the container.
  • Associate the container with an application object. This application object represents a J2EE enterprise application and may contain multiple EJBs and web contexts.
If all EJBs are successfully deployed, the application is started which in turn starts all containers and makes the EJBs available to clients. If any EJB fails to deploy, a deployment exception is thrown and the deployment module is failed. Container configuration information

JBoss externalizes most if not all of the setup of the EJB containers using an XML file that conforms to the jboss_4_0.dtd. The section DTD that relates to container configuration information is shown in Figure 30.4, “The jboss_4_0 DTD elements related to container configuration.”.
The container-configuration element and its subelements specify container configuration settings for a type of container as given by the container-name element. Each configuration specifies information such as the default invoker type, the container interceptor makeup, instance caches/pools and their sizes, persistence manager, security, and so on. Because this is a large amount of information that requires a detailed understanding of the JBoss container architecture, JBoss ships with a standard configuration for the four types of EJBs. This configuration file is called standardjboss.xml and it is located in the conf directory of any configuration file set that uses EJBs. The following is a sample of container-configuration from standardjboss.xml.
    <container-name>Standard CMP 2.x EntityBean</container-name>
        <interceptor metricsEnabled="true">
These two examples demonstrate how extensive the container configuration options are. The container configuration information can be specified at two levels. The first is in the standardjboss.xml file contained in the configuration file set directory. The second is at the EJB JAR level. By placing a jboss.xml file in the EJB JAR META-INF directory, you can specify either overrides for container configurations in the standardjboss.xml file, or entirely new named container configurations. This provides great flexibility in the configuration of containers. As you have seen, all container configuration attributes have been externalized and as such are easily modifiable. Knowledgeable developers can even implement specialized container components, such as instance pools or caches, and easily integrate them with the standard container configurations to optimize behavior for a particular application or environment.
How an EJB deployment chooses its container configuration is based on the explicit or implicit jboss/enterprise-beans/<type>/configuration-name element. The configuration-name element is a link to a container-configurations/container-configuration element. It specifies which container configuration to use for the referring EJB. The link is from a configuration-name element to a container-name element.
You are able to specify container configurations per class of EJB by including a container-configuration element in the EJB definition. Typically one does not define completely new container configurations, although this is supported. The typical usage of a jboss.xml level container-configuration is to override one or more aspects of a container-configuration coming from the standardjboss.xml descriptor. This is done by specifying container-configuration that references the name of an existing standardjboss.xmlcontainer-configuration/container-name as the value for the container-configuration/extends attribute. The following example shows an example of defining a new Secured Stateless SessionBean configuration that is an extension of the Standard Stateless SessionBean configuration.
<?xml version="1.0"?>
            <configuration-name>Secured Stateless SessionBean</configuration-name>
            <!-- ... -->
        <container-configuration extends="Standard Stateless SessionBean">
            <container-name>Secured Stateless SessionBean</container-name>
            <!-- Override the container security domain -->
If an EJB does not provide a container configuration specification in the deployment unit EJB JAR, the container factory chooses a container configuration from the standardjboss.xml descriptor based on the type of the EJB. So, in reality there is an implicit configuration-name element for every type of EJB, and the mappings from the EJB type to default container configuration name are as follows:
  • container-managed persistence entity version 2.0 = Standard CMP 2.x EntityBean
  • container-managed persistence entity version 1.1 = Standard CMP EntityBean
  • bean-managed persistence entity = Standard BMP EntityBean
  • stateless session = Standard Stateless SessionBean
  • stateful session = Standard Stateful SessionBean
  • message driven = Standard Message Driven Bean
It is not necessary to indicate which container configuration an EJB is using if you want to use the default based on the bean type. It probably provides for a more self-contained descriptor to include the configuration-name element, but this is purely a matter of style.
Now that you know how to specify which container configuration an EJB is using and can define a deployment unit level override, we now will look at the container-configuration child elements in the following sections. A number of the elements specify interface class implementations whose configuration is affected by other elements, so before starting in on the configuration elements you need to understand the org.jboss.metadata.XmlLoadable interface.
The XmlLoadable interface is a simple interface that consists of a single method. The interface definition is:
import org.w3c.dom.Element;
public interface XmlLoadable
    public void importXml(Element element) throws Exception;
Classes implement this interface to allow their configuration to be specified via an XML document fragment. The root element of the document fragment is what would be passed to the importXml method. You will see a few examples of this as the container configuration elements are described in the following sections. The container-name element
The container-name element specifies a unique name for a given configuration. EJBs link to a particular container configuration by setting their configuration-name element to the value of the container-name for the container configuration. The call-logging element
The call-logging element expects a boolean (true or false) as its value to indicate whether or not the LogInterceptor should log method calls to a container. This is somewhat obsolete with the change to log4j, which provides a fine-grained logging API. The invoker-proxy-binding-name element
The invoker-proxy-binding-name element specifies the name of the default invoker to use. In the absence of a bean level invoker-bindings specification, the invoker-proxy-binding whose name matches the invoker-proxy-binding-name element value will be used to create home and remote proxies. The sync-on-commit-only element
This configures a performance optimization that will cause entity bean state to be synchronized with the database only at commit time. Normally the state of all the beans in a transaction would need to be synchronized when an finder method is called or when an remove method is called, for example. insert-after-ejb-post-create
This is another entity bean optimization which cause the database insert command for a new entity bean to be delayed until the ejbPostCreate method is called. This allows normal CMP fields as well as CMR fields to be set in a single insert, instead of the default insert followed by an update, which allows removes the requirement for relation ship fields to allow null values. call-ejb-store-on-clean
By the specification the container is required to call ejbStore method on an entity bean instance when transaction commits even if the instance was not modified in the transaction. Setting this to false will cause JBoss to only call ejbStore for dirty objects. The container-interceptors Element
The container-interceptors element specifies one or more interceptor elements that are to be configured as the method interceptor chain for the container. The value of the interceptor element is a fully qualified class name of an org.jboss.ejb.Interceptor interface implementation. The container interceptors form a linked-list structure through which EJB method invocations pass. The first interceptor in the chain is invoked when the MBeanServer passes a method invocation to the container. The last interceptor invokes the business method on the bean. We will discuss the Interceptor interface latter in this chapter when we talk about the container plug-in framework. Generally, care must be taken when changing an existing standard EJB interceptor configuration as the EJB contract regarding security, transactions, persistence, and thread safety derive from the interceptors. The instance-pool element
The instance-pool element specifies the fully qualified class name of an org.jboss.ejb.InstancePool interface implementation to use as the container InstancePool. We will discuss the InstancePool interface in detail latter in this chapter when we talk about the container plug-in framework. The container-pool-conf element
The container-pool-conf is passed to the InstancePool implementation class given by the instance-pool element if it implements the XmlLoadable interface. All current JBoss InstancePool implementations derive from the org.jboss.ejb.plugins.AbstractInstancePool class which provides support for elements shown in Figure 30.5, “The container-pool-conf element DTD”.
The container-pool-conf element DTD

Figure 30.5. The container-pool-conf element DTD

  • MinimumSize: The MinimumSize element gives the minimum number of instances to keep in the pool, although JBoss does not currently seed an InstancePool to the MinimumSize value.
  • MaximumSize: The MaximumSize specifies the maximum number of pool instances that are allowed. The default use of MaximumSize may not be what you expect. The pool MaximumSize is the maximum number of EJB instances that are kept available, but additional instances can be created if the number of concurrent requests exceeds the MaximumSize value.
  • strictMaximumSize: If you want to limit the maximum concurrency of an EJB to the pool MaximumSize, you need to set the strictMaximumSize element to true. When strictMaximumSize is true, only MaximumSize EJB instances may be active. When there are MaximumSize active instances, any subsequent requests will be blocked until an instance is freed back to the pool. The default value for strictMaximumSize is false.
  • strictTimeout: How long a request blocks waiting for an instance pool object is controlled by the strictTimeout element. The strictTimeout defines the time in milliseconds to wait for an instance to be returned to the pool when there are MaximumSize active instances. A value less than or equal to 0 will mean not to wait at all. When a request times out waiting for an instance a java.rmi.ServerException is generated and the call aborted. This is parsed as a Long so the maximum possible wait time is 9,223,372,036,854,775,807 or about 292,471,208 years, and this is the default value. The instance-cache element
The instance-cache element specifies the fully qualified class name of the org.jboss.ejb.InstanceCache interface implementation. This element is only meaningful for entity and stateful session beans as these are the only EJB types that have an associated identity. We will discuss the InstanceCache interface in detail latter in this chapter when we talk about the container plug-in framework. The container-cache-conf element
The container-cache-conf element is passed to the InstanceCache implementation if it supports the XmlLoadable interface. All current JBoss InstanceCache implementations derive from the org.jboss.ejb.plugins.AbstractInstanceCache class which provides support for the XmlLoadable interface and uses the cache-policy child element as the fully qualified class name of an org.jboss.util.CachePolicy implementation that is used as the instance cache store. The cache-policy-conf child element is passed to the CachePolicy implementation if it supports the XmlLoadable interface. If it does not, the cache-policy-conf will silently be ignored.
There are two JBoss implementations of CachePolicy used by the standardjboss.xml configuration that support the current array of cache-policy-conf child elements. The classes are org.jboss.ejb.plugins.LRUEnterpriseContextCachePolicy and org.jboss.ejb.plugins.LRUStatefulContextCachePolicy. The LRUEnterpriseContextCachePolicy is used by entity bean containers while the LRUStatefulContextCachePolicy is used by stateful session bean containers. Both cache policies support the following cache-policy-conf child elements, shown in Figure 30.6, “The container-cache-conf element DTD”.
The container-cache-conf element DTD

Figure 30.6. The container-cache-conf element DTD

  • min-capacity: specifies the minimum capacity of this cache
  • max-capacity: specifies the maximum capacity of the cache, which cannot be less than min-capacity.
  • overager-period: specifies the period in seconds between runs of the overager task. The purpose of the overager task is to see if the cache contains beans with an age greater than the max-bean-age element value. Any beans meeting this criterion will be passivated.
  • max-bean-age: specifies the maximum period of inactivity in seconds a bean can have before it will be passivated by the overager process.
  • resizer-period: specifies the period in seconds between runs of the resizer task. The purpose of the resizer task is to contract or expand the cache capacity based on the remaining three element values in the following way. When the resizer task executes it checks the current period between cache misses, and if the period is less than the min-cache-miss-period value the cache is expanded up to the max-capacity value using the cache-load-factor. If instead the period between cache misses is greater than the max-cache-miss-period value the cache is contracted using the cache-load-factor.
  • max-cache-miss-period: specifies the time period in seconds in which a cache miss should signal that the cache capacity be contracted. It is equivalent to the minimum miss rate that will be tolerated before the cache is contracted.
  • min-cache-miss-period: specifies the time period in seconds in which a cache miss should signal that the cache capacity be expanded. It is equivalent to the maximum miss rate that will be tolerated before the cache is expanded.
  • cache-load-factor: specifies the factor by which the cache capacity is contracted and expanded. The factor should be less than 1. When the cache is contracted the capacity is reduced so that the current ratio of beans to cache capacity is equal to the cache-load-factor value. When the cache is expanded the new capacity is determined as current-capacity * 1/cache-load-factor. The actual expansion factor may be as high as 2 based on an internal algorithm based on the number of cache misses. The higher the cache miss rate the closer the true expansion factor will be to 2.
The LRUStatefulContextCachePolicy also supports the remaining child elements:
  • remover-period: specifies the period in seconds between runs of the remover task. The remover task removes passivated beans that have not been accessed in more than max-bean-life seconds. This task prevents stateful session beans that were not removed by users from filling up the passivation store.
  • max-bean-life: specifies the maximum period in seconds that a bean can exist inactive. After this period, as a result, the bean will be removed from the passivation store.
An alternative cache policy implementation is the org.jboss.ejb.plugins.NoPassivationCachePolicy class, which simply never passivates instances. It uses an in-memory HashMap implementation that never discards instances unless they are explicitly removed. This class does not support any of the cache-policy-conf configuration elements. The persistence-manager element
The persistence-manager element value specifies the fully qualified class name of the persistence manager implementation. The type of the implementation depends on the type of EJB. For stateful session beans it must be an implementation of the org.jboss.ejb.StatefulSessionPersistenceManager interface. For BMP entity beans it must be an implementation of the org.jboss.ejb.EntityPersistenceManager interface, while for CMP entity beans it must be an implementation of the org.jboss.ejb.EntityPersistenceStore interface. The web-class-loader Element
The web-class-loader element specifies a subclass of org.jboss.web.WebClassLoader that is used in conjunction with the WebService MBean to allow dynamic loading of resources and classes from deployed ears, EJB JARs and WARs. A WebClassLoader is associated with a Container and must have an org.jboss.mx.loading.UnifiedClassLoader as its parent. It overrides the getURLs() method to return a different set of URLs for remote loading than what is used for local loading.
WebClassLoader has two methods meant to be overridden by subclasses: getKey() and getBytes(). The latter is a no-op in this implementation and should be overridden by subclasses with bytecode generation ability, such as the classloader used by the iiop module.
WebClassLoader subclasses must have a constructor with the same signature as the WebClassLoader(ObjectName containerName, UnifiedClassLoader parent) constructor. The locking-policy element
The locking-policy element gives the fully qualified class name of the EJB lock implementation to use. This class must implement the org.jboss.ejb.BeanLock interface. The current JBoss versions include:
  • org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock: an implementation that holds threads awaiting the transactional lock to be freed in a fair FIFO queue. Non-transactional threads are also put into this wait queue as well. This class pops the next waiting transaction from the queue and notifies only those threads waiting associated with that transaction. The QueuedPessimisticEJBLock is the current default used by the standard configurations.
  • org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLockNoADE: This behaves the same as the QueuedPessimisticEJBLock except that deadlock detection is disabled.
  • org.jboss.ejb.plugins.lock.SimpleReadWriteEJBLock: This lock allows multiple read locks concurrently. Once a writer has requested the lock, future read-lock requests whose transactions do not already have the read lock will block until all writers are done; then all the waiting readers will concurrently go (depending on the reentrant setting / methodLock). A reader who promotes gets first crack at the write lock, ahead of other waiting writers. If there is already a reader that is promoting, we throw an inconsistent read exception. Of course, writers have to wait for all read-locks to release before taking the write lock.
  • org.jboss.ejb.plugins.lock.NoLock: an anti-locking policy used with the instance per transaction container configurations.
Locking and deadlock detection will be discussed in more detail in Section 30.4, “Entity Bean Locking and Deadlock Detection”. The commit-option and optiond-refresh-rate elements
The commit-option value specifies the EJB entity bean persistent storage commit option. It must be one of A, B, C or D.
  • A: the container caches the beans state between transactions. This option assumes that the container is the only user accessing the persistent store. This assumption allows the container to synchronize the in-memory state from the persistent storage only when absolutely necessary. This occurs before the first business method executes on a found bean or after the bean is passivated and reactivated to serve another business method. This behavior is independent of whether the business method executes inside a transaction context.
  • B: the container caches the bean state between transactions. However, unlike option A the container does not assume exclusive access to the persistent store. Therefore, the container will synchronize the in-memory state at the beginning of each transaction. Thus, business methods executing in a transaction context do not see much benefit from the container caching the bean, whereas business methods executing outside a transaction context (transaction attributes Never, NotSupported or Supports) access the cached (and potentially invalid) state of the bean.
  • C: the container does not cache bean instances. The in-memory state must be synchronized on every transaction start. For business methods executing outside a transaction the synchronization is still performed, but the ejbLoad executes in the same transaction context as that of the caller.
  • D: is a JBoss-specific commit option which is not described in the EJB specification. It is a lazy read scheme where bean state is cached between transactions as with option A, but the state is periodically re-synchronized with that of the persistent store. The default time between reloads is 30 seconds, but may configured using the optiond-refresh-rate element. The security-domain element
The security-domain element specifies the JNDI name of the object that implements the org.jboss.security.AuthenticationManager and org.jboss.security.RealmMapping interfaces. It is more typical to specify the security-domain under the jboss root element so that all EJBs in a given deployment are secured in the same manner. However, it is possible to configure the security domain for each bean configuration. cluster-config
The cluster-config element allows to specify cluster specific settings for all EJBs that use the container configuration. Specification of the cluster configuration may be done at the container configuration level or at the individual EJB deployment level.
  • partition-name: The partition-name element indicates where to find the org.jboss.ha.framework.interfaces.HAPartition interface to be used by the container to exchange clustering information. This is not the full JNDI name under which HAPartition is bound. Rather, it should correspond to the PartitionName attribute of the ClusterPartitionMBean service that is managing the desired cluster. The actual JNDI name of the HAPartition binding will be formed by appending /HASessionState/ to the partition-name value. The default value is DefaultPartition.
  • home-load-balance-policy: The home-load-balance-policy element indicates the Java class name to be used to load balance calls made on the home proxy. The class must implement the org.jboss.ha.framework.interface.LoadBalancePolicy interface. The default policy is org.jboss.ha.framework.interfaces.RoundRobin.
  • bean-load-balance-policy: The bean-load-balance-policy element indicates the java class name to be used to load balance calls in the bean proxy. The class must implement the org.jboss.ha.framework.interface.LoadBalancePolicy interface. For entity beans and stateful session beans, the default is org.jboss.ha.framework.interfaces.FirstAvailavble. For stateless session beans, org.jboss.ha.framework.interfaces.RoundRobin.
  • session-state-manager-jndi-name: The session-state-manager-jndi-name element indicates the name of the org.jboss.ha.framework.interfaces.HASessionState to be used by the container as a backend for state session management in the cluster. Unlike the partition-name element, this is a JNDI name under which the HASessionState implementation is bound. The default location used is /HASessionState/Default. The depends element
The depends element gives a JMX ObjectName of a service on which the container or EJB depends. Specification of explicit dependencies on other services avoids having to rely on the deployment order being after the required services are started.