13

I have developed a multithreaded web application that runs in Tomcat. But I cannot use

shutdown.bat

Tomcat didn't stop gracefully. In the debugger I saw that threads continue to run after shutdown command. Do I have to fix my application code to meet special requirements ? Thanks.

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
user710818
  • 23,228
  • 58
  • 149
  • 207

3 Answers3

12

... and to tie the other responses to the workings of Java Servlet environments;

if you don't declare your threads as daemon threads, the way to signal the server shutdown to the threads is to implement a ServletContextListener and configure it to your web application (web.xml). When Tomcat is shutting down, it will first shut down each application, which in turn will cause contextDestroyed() method of the listener to be called - and this is where you can signal your own threads that they should finish their work.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Juha Laiho
  • 596
  • 2
  • 8
  • Anyway to find out the threads which are causing this issue, would be helpful to me, as I am also hitting this issue. – Azim Jul 22 '16 at 08:05
  • You can use kill -3, jstack, or tomcat often dumps the stack traces in catalina.out. – ticktock Aug 03 '16 at 00:37
6

Any threads that are still running will keep the Java (Tomcat) process alive. Make sure all your threads exit. Once your threads exit, Tomcat will be able to shut down.

See the javadoc for Thread. Note the following:

The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
Community
  • 1
  • 1
Jack Edmonds
  • 31,931
  • 18
  • 65
  • 77
5

You need to cancel your threads, preferably by calling interrupt on them and making sure they are written in such a way that they respond to the interruption -- meaning, checking their interrupted flag and responding intelligently to InterruptedExceptions (not just eating them and continuing on).

The above advice assumes you don't want your threads to drop what they're doing immediately. If you are ok with that then make them daemons.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • 3
    Problem that I use 3rd part libraries that create own threads. And with these threads is problem. – user710818 Dec 30 '11 at 14:49
  • @user710818: yes, that's a bad problem. I'd hope the libraries would provide some way for you to tell them to do a graceful shutdown. – Nathan Hughes Dec 30 '11 at 14:58