Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Is there a SIMPLE way to "know" when tomcat server is stopping?

Posted on 2004-08-13
13
Medium Priority
?
316 Views
Last Modified: 2013-11-24
I've written an MVC Controller application that is utilizing a self authored dB connection pooler class.

As part of establishing a new pool I instantiate a subclass "reaper" thread that tests that pool's individual dB connections on a scheduled basis, reaping any that have died or are not returning an expected response.

I have a finalize method in my ConnectionPool class which sets a "timeToStop" boolean field in the reaper thread so that after the end of the current "sleep interval" the thread knows it's time to exit it's loop:

public void run() {
                while(!this.timeToStop) {
                      try {
                             this.totalSlept += 60000;
                             sleep(60000);
                      } catch( InterruptedException e) {
                             this.timeToStop = true;
                      }
                      if (this.totalSlept>=this.pool.reaperInterval){
                            this.totalSlept      = 0;
                            this.pool.reapConnections();
                      }
                }
          }

My problem is that when the tomcat server stops, my ConnectionPool class's "finalize()" method is not being called.

#1) worth 250:  Can anyone explain why my classes finalize() isn't being called when the Tomcat Server is stopping?

#2) worth 250: Can someone give me a SIMPLE (if at all possible: "static") field that I can monitor in my thead to know that the tomcat server is stopping?  If not, is there another way to "know" when the tomcat server is stopping so that I can end my thread loop?

THANKS!
0
Comment
Question by:ZacWolf
  • 5
  • 3
  • 2
  • +3
13 Comments
 
LVL 5

Accepted Solution

by:
TrekkyLeaper earned 1000 total points
ID: 11795024
I can answer the first one. finalize is only called AFTER an object has been marked as collectible. It will only be called if the object needs to be cleaned up. When you are shutting down, you are probably not getting to a memory-usage point where the garbage collector feels the need to clean up the instance. In short, there is no guarantee that an object will ever be collected and (depending on the collector) there is an even smaller chance that the finalize method will be called. You may also want to look at http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21043718.html in case there's anything more said there.
0
 

Author Comment

by:ZacWolf
ID: 11795619
Great thanks, that definately answers question #1, I'll award the point when I get an answer on #2.  Thanks again -Zac
0
 
LVL 7

Expert Comment

by:JugglerW
ID: 11796261
You can start your thread as a deamon (setDeamon( true ) when it will automatically terminate if main thread terminates.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 7

Assisted Solution

by:JugglerW
JugglerW earned 900 total points
ID: 11796302
How do you run your code in tomcat?
As a servlet? If yes you can overwrite the destroy method of your servlet.
0
 
LVL 7

Expert Comment

by:JugglerW
ID: 11796317
Ooops just saw typo: its setDaemon( true )
0
 

Author Comment

by:ZacWolf
ID: 11797363
JugglerW:
Yeah I can I setDaemon(true), but the point is to do some cleanup stuff prior to just "dying".

Yes, the code runs as a MVC servlet...
I'm not familiar with the "destroy" method.  Let me do some web searching on that.  Thanks, this sounds like what I need...

-Zac
0
 
LVL 92

Expert Comment

by:objects
ID: 11797824
1. You shouldn't rely on finalize() being called.

2. destroy() is what you want
0
 
LVL 28

Assisted Solution

by:rrz
rrz earned 100 total points
ID: 11798048
Or    contextDestroyed(ServletContextEvent sce)    
if you used a  ServletContextListener                rrz
0
 
LVL 5

Expert Comment

by:PointyEars
ID: 11799224
I wrote the following short program to get the pid of Tomcat.  The idea is to spawn a process that executes the "ps" command.  The pid of tomcat can be then obtained from the output of the command.  I know, it is a bit "dirty", but it works...

It doesn't work under Windows, where I presume you should use "tasklist" instead of "ps".

import java.io.*;
class TomcatPID {
  public static void main(String[] args) throws java.io.IOException {
    Process       proc = null;

    try {
      proc = Runtime.getRuntime().exec("ps -x");
      }
    catch (Exception e) {
      System.out.println(e.getMessage());
      }

    InputStream          pStdout = proc.getInputStream();
    InputStreamReader    pStdoutReader = new InputStreamReader(pStdout);
    LineNumberReader     pStdoutLine = new LineNumberReader(pStdoutReader);
    int                  k = -1;
    String               line = pStdoutLine.readLine();
    int                  pid = 0;

    while (line != null  &&  pid == 0) {
      k++;
      if (line.indexOf("jakarta-tomcat") > 0) {
        System.out.println(k + ": " + line);
        pid = Integer.parseInt(line.substring(0, line.indexOf(" ")));
        }
      else {
        line = pStdoutLine.readLine();
        }
      }

    System.out.println("pid = '" + pid + "'");
    }
  }
0
 
LVL 5

Expert Comment

by:PointyEars
ID: 11799242
Sorry, I forgot to say: when the program doesn't find tomcat's pid, it means that tomcat is not running :-)
0
 
LVL 7

Expert Comment

by:JugglerW
ID: 11799583
@PointyEars (BTW: Nice name :-) )

Think that will not work because the code runs as a servlet in the same VM as Tomcat itself, so if tomcat has terminated you'll have no chance to spawn your process ....

0
 

Author Comment

by:ZacWolf
ID: 11799786
Thanks everyone!

JugglerW is right PointyEars, the problem with the Tomcat shutdown is that it happens pretty quickly and pretty much wholescale "kills" any threads that aren't in a "sleep" state (sans daemons).  

I even tried the whole java.lang.Runtime.getRuntime().addShutdownHook() thing with no success.

I think the destroy() method is going to be my best bet.

Thanks again,
-Zac
0
 
LVL 7

Expert Comment

by:JugglerW
ID: 11799885
Thanks :-)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question