title: Correct way to create task threads in tomcat at startup
body: <p>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 <em>at time of tomcat startup</em> that have a <em>specific purpose</em>.  I am using a linux system.</p>
  
  <p>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.</p>
  
  <p>There are a few approaches I know that I could take:</p>
  
  <ol>
  <li><p>Create a process running <em>outside</em> 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 <code>ServletContext</code>, and to not have to ser/des data across a communication channel.</p></li>
  <li><p>Spawn two threads in the <code>init</code> method of one of my servlets.  This seems dirty and hackish, but it would definitely get the job done.</p></li>
  <li><p>Create a <code>ServletContextListener</code> that extends a <code>ThreadPoolExecutor</code> or other <code>ExexutorService</code>.  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 an <code>ExecutorService</code> is really more meant for executing <code>Runnable</code>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.</p></li>
  </ol>
  
  <p>Maybe there are more methods that I do not know about, or a correct way to implement one of the above.</p>