开发者

How do I kill a long-running servlet process from another servlet?

I have a Java servlet that runs a database query that may take several minutes to run before attempting to write to the response stream. During the database query the user may have disconnected (thus making the query useless).

Since I can't kill it in the database thread, I'm trying to kill it from开发者_StackOverflow社区 another thread. Do any of the servlet containers provide a recommended way of "canceling" or "killing" a request thread? If I carry a reference to the Thread around, can I force an interrupt or similar?


Tour question is not about java threads. It is about killing database query into the database. I say it because as far as I understand your question what happens is that client sends HTTP request to servlet that performs JDBC connection and runs query that takes a lot of time. So, java does not work this time. The DB does. This means that you have to kill the DB query into the DB. How to do this? This depends on your database. MySql (for example) has a kind of command line shell that allows retrieving the list of current queries and terminating the queries. So this is what you can do. Your second servelet may connect to MySql, retrieve running queries, identify which one should be killed (this is application specific functionality) and kill it. I believe that once you do this the first servlet will get JDBCException and can exit.

This is the way to show list of running queries: http://www.electrictoolbox.com/show-running-queries-mysql/

Here is how to kill query: http://dev.mysql.com/doc/refman/5.0/en/kill.html

And the last note that probably should be the first. Check why is your query taking so long time? IMHO in most cases it means that your schema is not optimal or some index is missing. Generally, if your query takes more than 0.1 seconds check your DB schema.


  1. If you are running a hour long DB query , you should not in first place call from a servlet ,as you response stream will timeout, you will get 504.
  2. May i know what this query is doing, something involving calculation and large updates or inserts.
  3. you should try placing this query in DB JOBS.


You can java.sql.Statement.cancel() you will have to have the running statements registered somewhere (ServletContext or whatever structure you find fit) and unregistered upon completion.

The JDBC driver must support this method (cancel()) as well, I don't know if PostgreSQL supports it, though

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜