Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Interrupting a thread executing (JDBC) Connection.executeQuery()?  RSS feed

 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I'm wondering whether it is possible to interrupt a thread that is in the middle of executing a database query using java.sql.Connection#executeQuery()...?
What I'm trying to do is to have a timeout for the query - if the specified time limit is reached, the query processing is interrupted and some kind of "you interrupted" page is shown to the browser.
I was thinking about launching one thread for performing the executeQuery() and another for the timer. The timer thread would then call sqlThread.interrupt().
Is this ok? Is there a better way?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that instead of using Thread's interrupt() method, the preferred method would be to invoke cancel() on the Statement that's being executed. If the DB doesn't support that, you may be on your own. I suspect that for many DB drivers, invoking interrupt() will have no effect. (Note that exectueQuery() does not throw InterruptedException.) You may wish to try close()-ing the Statement, or even the Connection, as an alternative. This will probably cause the executeQuery() to throw a SQLException, which you can then catch and deal with.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that instead of using Thread's interrupt() method, the preferred method would be to invoke cancel() on the Statement that's being executed. If the DB doesn't support that, you may be on your own.

Thanks a zillion! I had completely forgotten to check the statement objects' APIs. I'll try the cancel().

I suspect that for many DB drivers, invoking interrupt() will have no effect.

Yes. I took a glance on the threading stuff in the language specification and interpreted that interrupt() can't "cut in" unless the thread being interrupted is sleeping (or is going to sleep). So, if my interpretation was correct, as a rule the interrupt() wouldn't work (with some weird JDBC driver, it might).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!