The moose likes Threads and Synchronization and the fly likes Interrupting a thread executing (JDBC) Connection.executeQuery()? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Interrupting a thread executing (JDBC) Connection.executeQuery()?" Watch "Interrupting a thread executing (JDBC) Connection.executeQuery()?" New topic
Author

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

Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11945
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?


Author of Test Driven (Manning Publications, 2007) [Blog] [HowToAskQuestionsOnJavaRanch]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18652
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.


"I'm not back." - Bill Harding, Twister
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11945
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).
 
 
subject: Interrupting a thread executing (JDBC) Connection.executeQuery()?
 
Threads others viewed
reusing the Statement object
SQL error
Flow of Code Control
Time-based responses in a JFrame?
Threads join() method
IntelliJ Java IDE