This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I' my trying to implement some piece of code which allows to execute arbitrary (prepared) statements with respect to a given timeout value. So far everthing works fine. The queries are executed, the timeouts are respected and the statements in question get cancelled with an SQLException when the timeout limit is reached.
The only problem is that using this mechanism I don't see a possibility to distungish between SQLExceptions caused by a timeout and other SQLExceptions thrown during execution of a statement. Depending on the cause for an exception the calling code of my code should get a different result so it's necessary to distinguish the cause for an exception. The only possibility I see at the moment is to rely on the error message of the exception which doesn't seem to be a really good idea.
Do you have any ideas how to handle this cleanly?
Another solution I can think about would be to use the cancel() method in Statement and use another thread to take care for correct cancellation of the statement in case of a timeout (so that not only the Java code but also the process on the database server gets cancelled). But I'm unsure how to implement this correctly.
thanks for your answer! According to the API documentation of java.sql.Statement an unspecified SQLException is thrown but I guess you're right, depending on the vendor a more appropriate SQLTimeoutException _COULD_ be thrown. Unfortunately this is an implementation detail I didn't want to rely on.
So now I have used a workaround or maybe an even better alternative to the JDBC based approach. I don't use the query timeout of the JDBC API at all and instead execute the SQL statements with the help of a FutureTask and ExecutorService in a background thread and make use of its timeout mechanism which reports timeouts precisely!
I don't use the query timeout of the JDBC API at all and instead execute the SQL statements with the help of a FutureTask and ExecutorService in a background thread and make use of its timeout mechanism which reports timeouts precisely!