...
This noncompliant code example uses a volatile done
flag to indicate that whether is safe to shut down the thread, as suggested in rule THI05-J. Do not use Thread.stop() to terminate threads. However, when the thread is blocked on network I/O as a consequence of invoking the readLine()
method, it cannot respond to the newly-set flag until the network I/O is complete. Consequently, thread termination may be indefinitely delayed.
Code Block | ||
---|---|---|
| ||
// Thread-safe class
public final class SocketReader implements Runnable {
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
@Override 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
}
}
|
...
This noncompliant code example is similar to the preceding example but uses thread interruption to shut down the thread. Network I/O on a java.net.Socket
is unresponsive to thread interruption.
Code Block | ||
---|---|---|
| ||
// Thread-safe class
public final class SocketReader implements Runnable {
// other methods...
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
}
}
|
...
This compliant solution terminates the blocking network I/O by closing the socket in the shutdown()
method. The readLine()
method throws a SocketException
when the socket is closed, consequently allowing the thread to proceed. Note that it is impossible to keep the connection alive while simultaneously halting the thread both cleanly and immediately.
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable {
// other methods...
public void readData() throws IOException {
String string;
try {
while ((string = in.readLine()) != null) {
// Blocks until end of stream (null)
}
} finally {
shutdown();
}
}
public void shutdown() throws IOException {
socket.close();
}
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();
}
}
|
...
This compliant solution uses an interruptible channel, java.nio.channels.SocketChannel
, instead of a Socket
connection. If the thread performing the network I/O 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 interrupted status is also set.
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable {
private final SocketChannel sc;
private final Object lock = new Object();
public SocketReader(String host, int port) throws IOException {
sc = SocketChannel.open(new InetSocketAddress(host, port));
}
@Override public void run() {
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
synchronized (lock) {
while (!Thread.interrupted()) {
sc.read(buf);
// ...
}
}
} catch (IOException ie) {
// Forward to handler
}
}
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();
}
}
|
...
This noncompliant code example shows a thread-safe DBConnector
class that creates one JDBC connection per thread. Each connection belongs to one thread and is not shared by other threads. This is a common use case because JDBC connections are intended to be single-threaded.
Code Block | ||
---|---|---|
| ||
public final class DBConnector implements Runnable {
private final String query;
DBConnector(String query) {
this.query = query;
}
@Override 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();
}
}
|
...
This compliant solution uses a ThreadLocal
wrapper around the connection so that a thread calling the initialValue()
method obtains a unique connection instance. This approach allows provision of a cancelStatement()
so that other threads or clients can interrupt a long-running query when required. The cancelStatement()
method invokes the Statement.cancel()
method.
Code Block | ||
---|---|---|
| ||
public final class DBConnector implements Runnable { private final String query; private volatile Statement stmt; DBConnector(String query) { this.query = query; } if (getConnection() != null) { private static final ThreadLocal<Connection> connectionHolder = try { stmt = getConnection().createStatement(); } catch (SQLException e) { // Forward to handler new ThreadLocal<Connection>() }{ } } private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() { Connection connection = null; @Override public Connection initialValue() { try { // ... connection = DriverManager.getConnection( "jdbc:driver:name", "username", "password" ); } catch (SQLException e) { // Forward to handler } return connection; } }; public Connection getConnection() { return connectionHolder.get(); } public boolean cancelStatement() { // Allows client to cancel statementto cancel statement Statement tmpStmt = stmt; if (stmttmpStmt != null) { try { stmttmpStmt.cancel(); return true; } catch (SQLException e) { // Forward to handler } } return false; } @Override public void run() { try { if (getConnection() != null) { stmt = getConnection().createStatement(); } if (stmt == null || (stmt.getConnection() != getConnection())) { throw new IllegalStateException(); } 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.cancelStatement(); } } |
...
[API 2006] | Class |
24.3, Stopping a Thread | |
Java Thread Primitive Deprecation | |
[JPL 2006] | 14.12.1, Don't Stop; 23.3.3, Shutdown Strategies |
2.4, Two Approaches to Stopping a Thread | |
Chapter 7, Cancellation and Shutdown |