0

Tomcat failed to start when calling Thread.sleep inside servlet on server startup.

There is a Servet which is loaded at server start up. Inside the init method of servlet, sendMail method of MailSenderUtility class is called. Inside the sendMail method I have called Thread.sleep() method to sleep the program for a calculated time if it is not 8 PM.

Due to this code (Thread.sleep) server does not getting started. If I delete the Thread.sleep statement, it is working fine.

Please help and let me know if there is better way to do it. For your knowledge I can not use Quartz and Java Timer class for my scheduler due to some limitations.

Thank to you all for support.

Dheeraj

Dheeraj
  • 1
  • 1

2 Answers2

2

Dheeraj you cant "stop" the thread responsible for the initialization. Do it somewhere else since Servlet object is not suitable for this.

What you need is ContextListener. Well described also here.

Good luck!

Community
  • 1
  • 1
lzap
  • 14,745
  • 10
  • 62
  • 100
2

Obviously you are putting the main thread to sleep.

Instead you should create a separate thread and run MailSenderUtility on it. Then you can sleep this thread without affecting the main initialization thread.

A simple example:

    new Thread(new Runnable(){
        public void run() {
            // start MailSenderUtility here
        }
    }).start();
Peter Knego
  • 78,855
  • 10
  • 118
  • 147
  • Well yeah but never forget to properly stop the thread otherwise you run into issues during context redeployments (errors in the tomcat log). I hihgly recommend to use ContextListener and to properly implement its contextDestroyed method. – lzap Feb 24 '11 at 10:11
  • Agreed. Your solution is undoubtedly cleaner. Mine is just a quick hack. – Peter Knego Feb 24 '11 at 10:12