Solved

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

Posted on 2004-08-13
13
293 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
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 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
session migration servlets 2 36
varialbe initialization 11 32
configure dependency in POM for new database 3 25
Java: anonymous class 4 17
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…

785 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