Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2004-08-13
13
Medium Priority
?
315 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 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
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

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.
Suggested Courses

670 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