Having read a lot of different things and not being totally familiar with the correct terms for some of these things, I am wondering what the correct way is for creating threads at time of tomcat startup that have a specific purpose. I am using a linux system.
I am not trying to create a thread from a servlet, and I have a good idea of why this is bad. When tomcat starts up, I want two different threads that have a distinct purpose to start. The first thread runs on a period, every 30 minutes, to audit back-end data. The second thread is responsible for sending emails. When a request runs a servlet where an email must be sent, instead of holding up the servlet waiting for the email to be sent, I want to send a request to this email thread and move on. So one runs periodically, and one runs on demand. I never need to increase the number of threads performing these tasks, I just need these two going, and for it to be going as long as the webapp is running, and if the webapp has to halt, I don't really care about graceful shutdown.
There are a few approaches I know that I could take:
Create a process running outside of tomcat and define a way to communicate with that process from my servlet. I'd like to avoid this if possible, because I'd like for these two threads to first be directly associated with start up and shut down of the webapp, and for them to be able to access data in the
ServletContext
, and to not have to ser/des data across a communication channel.Spawn two threads in the
init
method of one of my servlets. This seems dirty and hackish, but it would definitely get the job done.Create a
ServletContextListener
that extends aThreadPoolExecutor
or otherExexutorService
. This seems appealing and correct, and I suppose I could do a fixed thread pool of 2 threads because I don't need any more. But is this the recommended way to do what I am trying? I understand that anExecutorService
is really more meant for executingRunnable
s on the fly without having to lose the overhead of creating a thread. I don't know if that is totally right, but if it is, I would not be using an executor for its meant purpose.
Maybe there are more methods that I do not know about, or a correct way to implement one of the above.