...
| Code Block | ||
|---|---|---|
| ||
class DBConnector implements Runnable {
final String query;
private final Object lock = new Object();
private boolean isRunning = false;
private class MultipleUseException extends RuntimeException {};
DBConnector(String query) {
this.query = query;
}
public void run() {
synchronized (lock) {
if (isRunning) {
throw new MultipleUseException();
}
isRunning = true;
}
Connection con;
try {
// Username and password are hard coded for brevity
con = DriverManager.getConnection("jdbc:driver:name", "username","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
} catch (SQLException e) {
// Forward to handler
}
// ...
}
public static void main(String[] args) throws InterruptedException {
DBConnector connector = new DBConnector(/* suitable query */);
Thread thread = new Thread(connector);
thread.start();
Thread.sleep(5000);
thread.interrupt();
}
}
|
...