Thursday, June 17, 2004

Interruptible queries with Java

ONJava.com has a nice article with clean examples of several techniques, Interruptible Database Queries. The clean code includes:

public synchronized ResultSet executeQuery(Statement statement, String query) throws SQLException, InterruptedException { // Set query parameters synchronized (params) { params.statement = statement; params.query = query; params.pending = true; params.notify(); } synchronized (results) { try { // Wait for the query to complete while (!results.serviced) results.wait(); if (results.exception != null) throw results.exception; } catch (InterruptedException e) { cancel(); throw e; } finally { results.serviced = false; } return results.rs; } }

Read the whole article for the worker thread, cancel() and how to put it all together.

No comments: