...
This noncompliant code example uses a volatile done
flag to indicate that it is safe to shut down the thread, as suggested in CON13-J. Ensure that threads are stopped cleanly. However, this setting the flag does not help in terminating terminate the thread because the thread is blocked on network IO as a consequence of using the readLine()
method.
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable { // Thread-safe class
private final Socket socket;
private final BufferedReader in;
private volatile boolean done = false;
private final Object lock = new Object();
public SocketReader(String host, int port) throws IOException {
this.socket = new Socket(host, port);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
}
// Only one thread can use the socket at a particular time
public void run() {
try {
synchronized (lock) {
readData();
}
} catch (IOException ie) {
// Forward to handler
}
}
public void readData() throws IOException {
String string;
while (!done && (string = in.readLine()) != null) {
// Blocks until end of stream (null)
}
}
public void shutdown() {
done = true;
}
public static void main(String[] args) throws IOException, InterruptedException {
SocketReader reader = new SocketReader("somehost", 25);
Thread thread = new Thread(reader);
thread.start();
Thread.sleep(1000);
reader.shutdown(); // Shutdown the thread
}
}
|
Noncompliant Code Example (blocking IO, interruptible)
...
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable { // Thread-safe class
// ...
public void readData() throws IOException {
String string;
while (!Thread.interrupted() && (string = in.readLine()) != null) {
// Blocks until end of stream (null)
}
}
public static void main(String[] args) throws IOException, InterruptedException {
SocketReader reader = new SocketReader("somehost", 25);
Thread thread = new Thread(reader);
thread.start();
Thread.sleep(1000);
thread.interrupt(); // Interrupt the thread
}
}
|
Compliant Solution (close socket connection)
...
This compliant solution uses an interruptible channel, java.nio.channels.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.
...
This technique interrupts the current thread, however, it only stops the thread because the code polls the interrupted flag using the method Thread.interrupted()
, and shuts down the thread when it is interrupted. Using a SocketChannel
ensures that the condition in the while loop is tested as soon as an interruption is received, despite the read operation being a blocking operation. Invoking Similarly, invoking the interrupt()
method of a thread that is blocked because of a java.nio.channels.Selector
also causes the that thread to awaken.
Noncompliant Code Example (database connection)
...
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();
}
}
|
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 A similar mechanism is required for task cancellation mechanisms are required when using socket objects that are local to a method, such as sockets.
Unfortunately database connections, like sockets, are not inherently interruptible. So Consequently, this design does not permit a client to cancel a task by closing the resource it if the corresponding thread is blocked on a long running activity such as a join query.
...
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 nullcon value= isnull 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(); } } |
...