A particular timeout is provided for the stateful EJB. The @StatefulTimeout annotation establishes the duration time of a stateful EJB before returning to the pool when it doesn't receive calls by the clients. This is a sample of stateful timeout:
@Stateful
@StatefulTimeout(value = 15, unit = MILLISECONDS)
public class User {
private boolean registered = false;
public void register() {
registered = true;
}
public boolean isRegistered() {
return registered;
}
@Remove
public void remove() {
registered = false;
}
}
After 15 milliseconds, the container will execute the deletion of the stateful bean. To understand this operation, we can implement a method marked with the @Remove annotation seen in Chapter 4, Implementing Business Logic, and wait for 15 milliseconds. After this, the remove method will be executed. The remove can be tested through a client injecting the stateful:
...
@EJB
private User user;
...
user.register();
assertTrue("The stateful session is registered", user.isRegistered());
sleep(160);
try {
user.isRegistered();
fail();
} catch (NoSuchEJBException e) {
logger.info("The ejb is expired");
}
On the first time, the user represented by the stateful bean is registered because the register() method is started. Waiting for a little time, thanks to the sleep method of the thread class, we again tried to use the stateless but it was expired, so the NoSuchEJBException was thrown.