My client application needs to obtain some (live) statistics from a database table. The statistics are calculated by regularly (every 5 secs) polling the database for new/updated records in that table (the rows have a timestamp) and processing the modified/new rows. I would like to implement this functionality in the middle tier, so that there is only one "worker thread" polling the database and all clients get their statistics from that worker via a stateless session bean.
I've read that it is not ok to start threads from session beans, as the AS assumes it manages all threads autonomously. However, I really need to have a constantly running thread as long as there is at least one instance of stateless bean X available. I'd settle if the thread is constantly running throughout the lifetime of my application, i.e.:
- Have JBoss start a "worker" thread as soon as my EAR is deployed.
- Have JBoss stop this thread as soon as my EAR is undeployed.
- Allow a stateless session bean to obtain a reference to this thread object (e.g. via JNDI?) so that it may access data that the object holds (the statistics it calculated).
What is the "proper" way to implement this kind of stuff?