The recommendations suggested in the guideline CON13-J. Ensure that threads are stopped cleanly are insufficient to terminate a thread that is blocked on a blocking an operation such as involving network or file input-output (IO). Consequently, threads Threads and tasks should provide callers with an explicit termination mechanism to prevent denial of service vulnerabilities.
...
This noncompliant code example is similar to the preceding one, but uses thread interruption to indicate that it is safe to shut down the thread. Network IO is not responsive to thread interruption when a java.net.Socket
is being used.
...
This compliant solution resumes the thread , by having the shutdown()
method close the socket. As a result, the thread is bound to stop because the The readLine()
method will throw throws a SocketException
when the socet socket is closed which lets the thread proceed. Note that there is no way to keep the connection alive if the thread is to be cleanly halted immediately.
...
The finally
block executes after shutdown()
is called. Because the finally
block also calls the shutdown()
method, it is possible that the socket will be closed a second time, which twice. The second call has no effect .if the socket has already been closed.
When When performing asynchronous IO, a java.nio.channels.Selector
may also be brought out of the blocked state by either invoking its close()
or wakeup()
method.
A boolean
flag can be used (as shown earlier) if additional operations need to be performed after emerging from the blocked state. When supplementing the code with such a flag, the shutdown()
method should also set the flag to false so that the thread can cleanly exit from the while loop.
...
This compliant solution uses an interruptible channel, SocketChannel
, instead of a Socket
connection. If the thread performing the network IO is interrupted using the Thread.interrupt()
method while it is reading the data, the thread receives a ClosedByInterruptException
and the channel is closed immediately. The thread's interrupt status is also set.
...
Code Block | ||
---|---|---|
| ||
public final class DBConnector implements Runnable {
private final String query;
DBConnector(String query) {
this.query = query;
}
public void run() {
Connection connection;
try {
// Username and password are hard coded for brevity
connection = DriverManager.getConnection("jdbc:driver:name", "username", "password");
Statement stmt = connection.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();
}
}
|
Unfortunately database connections, like sockets, are not inherently interruptible. So this design does not permit a client to cancel a task by closing it if the corresponding thread is blocked on a long running activity such as a join query. Furthermore, it is important to provide a mechanism to close connections to prevent thread starvation, because there is a Other than helping thread cancellation, a mechanism to close connections also prevents thread starvation because threads can be allowed to fairly share the limited number of database connections available in the pool. Similar task cancellation mechanisms are required when using objects local to a method, such as sockets.
Unfortunately database connections, like sockets, are not inherently interruptible. So this design does not permit a client to cancel a task by closing it if the corresponding thread is blocked on a long running activity such as a join query.
Compliant Solution (ThreadLocal)
...
Code Block | ||
---|---|---|
| ||
public final class DBConnector implements Runnable { private final String query; DBConnector(String query) { this.query = query; } private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() { Connection connection = null; @Override public Connection initialValue() { try { // Username and password are hard coded for brevity connection = DriverManager.getConnection ("jdbc:driver:name", "username", "password"); } catch (SQLException e) { // Forward to handler } return connection; } @Override public void set(Connection con) { if(connection == null) { // Shuts down connection when null value is passed try { connection.close(); } catch (SQLException e) { // Forward to handler } } else { connection = con; } } }; public static Connection getConnection() { return connectionHolder.get(); } public static void shutdownConnection() { // Allows client to close connection anytime connectionHolder.set(null); } public void run() { Connection dbConnection = getConnection(); Statement stmt; try { stmt = dbConnection.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); connector.shutdown(); } } |
...