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 is replicated and synchronized across the cluster each time the state of a bean changes.
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. The definition of the @CacheConfig annotation is:
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
CacheManagerservice discussed in Section 19.2.3, “CacheManager service configuration”. By default, thesfsb-cacheconfiguration 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 maximum period of time a bean can go unused before the cache should passivate it (regardless of whether
maxSizebeans are cached). removalTimeoutSeconds- Specifies the maximum 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
@PrePassivateand@PostActivatecallbacks on the bean. By default this is set totrue, since replication involves serializing the bean, and preparing for and recovering from serialization is a common reason for implementing the callback methods.
The following is an example of a clustered EJB 3.0 stateful session bean implementation.
@Stateful
@Clustered
@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 like so:
<jboss>
<enterprise-beans>
<session>
<ejb-name>NonAnnotationStateful</ejb-name>
<clustered>true</clustered>
<cache-config>
<cache-max-size>5000</cache-max-size>
<remove-timeout-seconds>18000</remove-timeout-seconds>
</cache-config>
</session>
</enterprise-beans>
</jboss>