Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the EJB Timer Service use Singleton as standard?

I have been studying ejb recently and I am also reading about the timer service as well, but even though I have read about Stateless, Stateful and Singleton types of Session Beans, I still have some trouble to figure out what makes the Timer Service have a multiple instance attribute.

I have seen some examples around, and even the simplest ones use the Singleton Session Bean, so, If I were to write a simple program to test it, would it be ok to use a Stateless Bean or is it recommended to use a Singleton anyway? Also, if possible, can I have a case where a Stateless would not be optimal?

like image 956
M. K. Avatar asked Oct 18 '22 07:10

M. K.


1 Answers

Use a singleton if you want to ensure that all timeout callbacks are invoked on the same underlying bean instance. This is important if you want to maintain state in the bean instance itself, and you want to ensure that only one timeout callback can be invoked at a time (by default, the timeout callback will use the singleton's concurrency management settings, which by default is container-managed with a write lock, so only one method on the singleton can be invoked at a time).

Use a stateless if you want to allow multiple timeout callbacks to be invoked at once. The EJB container will create new bean instances if there are multiple timeout callbacks happening concurrently.

If you want to configure a non-persistent timer to begin running when the application begins running, then you can either use the @Schedule annotation on either a stateless or singleton bean, or you can use an @Singleton @Startup bean with an @PostConstruct (and if you want the stateless behavior, you can inject the stateless bean into the stateless bean and invoke a createTimer on the stateless session bean during startup).

like image 127
Brett Kail Avatar answered Oct 27 '22 10:10

Brett Kail