Configuring Timeout policies for your EJBs

In the most recent version of WildFly (20) it is now possible to configure a default timeout setting for all your Stateful beans. Let’s recap in this article all timeout policies you can define for your EJBs:

  • StatefulTimeout: This timeout policy is used to force passivation of Stateful beans which are inactive for a certain amount of time.
  • AccessTimeout: This timeout policy is used to specify the time period after which a queued request for a Stateful or Singleton Bean times out.

Let’s see more in detail how to configure these timeout policies and which beans can actually use them.

Configuring the Stateful Session Bean timeout

It is possible to configure a timeout for Stateful Session Beans which will cause the Beans to be passivated when they don’t receive calls from clients for a certain amount of time. The timeout can be configured at EJB level or using a default global stateful bean session timeout for all deployed stateful beans.

At EJB level, this can be done using the @javax.ejb.StatefulTimeout annotation as in this example:

@StatefulTimeout(value = 1000, unit = TimeUnit.MILLISECONDS)
public class PassivatingBean {
    
}  

Besides that, you can configure the Stateful Session Bean timeout using the **stateful-timeout** XML element in the ejb-jar.xml deployment descriptor. For example, to set a timeout value of 20 seconds:

<stateful-timeout>
     <timeout>20</timeout>
     <unit>Seconds</unit>
</stateful-timeout>

With WildFly 20, you can also define a global stateful timeout (which will be overridden by specific EJB StatefulTimeout settings) as follows:

/subsystem=ejb3:write-attribute(name=default-stateful-bean-session-timeout, value=10000)

In the above example, the default timeout for SFSB is set to 10 seconds.

Configuring the Access timeout for SFSBs and Singleton beans

Stateful and Singleton Session Beans have an access timeout value specified for managing concurrent access. As the name implies a **Singleton bean** is a Session Bean with a guarantee that there is at most one instance per JVM in the application.

This value is the period of time that a request to a session bean method can be blocked before it will timeout. Here’s how to set this value to 5000 ms:

/subsystem=ejb3/:write-attribute(name=default-stateful-bean-access-timeout,value=5000)

The timeout value and the time unit used can also be specified using the @javax.ejb.AccessTimeout annotation on the SFSB/Singleton method. It can be specified on the session bean (which applies to all the bean’s methods) and on specific methods to override the configuration for the bean.

Example:

@Singleton
public class Singleton_With_Timeout{
    @AccessTimeout(value = 5000, unit = java.util.concurrent.TimeUnit.MILLISECONDS)
    @Lock(LockType.WRITE)  
    public void doSomething(){
        
    }
}
Found the article helpful? if so please follow us on Socials