...
This noncompliant code example shows a thread-safe class DBConnector that creates a JDBC connection per thread, that is, the connection belonging to one thread is not shared by other threads. This is a common use-case because JDBC connections are not meant to be shared by multiple-threads.
| Code Block | ||
|---|---|---|
| ||
class DBConnector implements Runnable {
final String query;
DBConnector(String query) {
this.query = query;
}
public void run() {
Connection con;
try {
con = DriverManager.getConnection("jdbc:myDriver:name", "username","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
} catch (SQLException e) {
// Forward to handler
}
// ...
}
}
|
...