Recommendations discussed in the guideline CON13-J. Ensure that threads are stopped cleanly are insufficient to terminate a thread that is blocked on a blocking operation such as network or file input-output (IO). Consequently, threads and tasks should provide callers with an explicit termination mechanism to prevent denial of service vulnerabilities.
Noncompliant Code Example (blocking IO, volatile flag)
This noncompliant code example uses a volatile done
flag to indicate that it is safe to shutdown the thread, as suggested abovein CON13-J. Ensure that threads are stopped cleanly. However, this does not help in terminating the thread because it is blocked on some network IO as a consequence of using the readLine()
method.
...
This noncompliant code example uses thread interruption to indicate that it is safe to shutdown the thread, as suggested abovein CON13-J. Ensure that threads are stopped cleanly. However, this is not useful because the thread is blocked on some network IO as a consequence of using the readLine()
method. Network I/O is not responsive to thread interruption.
...
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:myDriverdriver: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(); } } |
...