Solved

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

Posted on 2004-08-13
13
296 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
hibernate example for saving data 19 74
jboss wildfly 10.1 10 419
difference between sorce folder and folder in eclipise 3 42
How to determine if a string is a valid SHA value 7 43
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
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 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…
This video teaches viewers about errors in exception handling.

756 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