23.2. Stateful Session Beans in EJB 3.0

Clustering stateful session beans is more complex than clustering their stateless counterparts since JBoss needs to manage the state information. The state of all stateful session beans are replicated and synchronized across the cluster each time the state of a bean changes.

23.2.1. The EJB application configuration

To cluster stateful session beans in EJB 3.0, you need to tag the bean implementation class with the @Clustered annotation, just as we did with the EJB 3.0 stateless session bean earlier. In contrast to stateless session beans, stateful session bean method invocations are load balanced using org.jboss.ha.client.loadbalance.aop.FirstAvailable policy, by default. Using this policy, methods invocations will stick to a randomly chosen node.
The @org.jboss.ejb3.annotation.CacheConfig annotation can also be applied to the bean to override the default caching behavior. Below is the definition of the @CacheConfig annotation:
public @interface CacheConfig
   String name() default "";
   int maxSize() default 10000;
   long idleTimeoutSeconds() default 300;   
   boolean replicationIsPassivation() default true;   
   long removalTimeoutSeconds() default 0;
  • name specifies the name of a cache configuration registered with the CacheManager service discussed in Section 23.2.3, “CacheManager service configuration”. By default, the sfsb-cache configuration will be used.
  • maxSize specifies the maximum number of beans that can cached before the cache should start passivating beans, using an LRU algorithm.
  • idleTimeoutSeconds specifies the max period of time a bean can go unused before the cache should passivate it (regardless of whether maxSize beans are cached.)
  • removalTimeoutSeconds specifies the max period of time a bean can go unused before the cache should remove it altogether.
  • replicationIsPassivation specifies whether the cache should consider a replication as being equivalent to a passivation, and invoke any @PrePassivate and @PostActivate callbacks on the bean. By default true, since replication involves serializing the bean, and preparing for and recovering from serialization is a common reason for implementing the callback methods.
Here is an example of a clustered EJB 3.0 stateful session bean implementation.
@CacheConfig(maxSize=5000, removalTimeoutSeconds=18000)
public class MyBean implements MySessionInt
   private int state = 0;

   public void increment()
      System.out.println("counter: " + (state++));
As with stateless beans, the @Clustered annotation can alternatively be omitted and the clustering configuration instead applied to jboss.xml: