Solved

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

Posted on 2004-08-13
13
289 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 250 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
 
LVL 7

Assisted Solution

by:JugglerW
JugglerW earned 225 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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 27

Assisted Solution

by:rrz
rrz earned 25 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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Unable to start eclipse ? 17 132
Responding to Java JComponent extended classes's resize event 4 51
Java SE 8u111  Lot of stuff broke 11 54
Windows 10 IE Certificate Issue 10 41
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

910 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now