...
This noncompliant code example uses a volatile done
flag to indicate that it is safe to shutdown the thread, as suggested in 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.
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();
}
}
|
...
This noncompliant code example uses thread interruption to indicate that it is safe to shutdown the thread, as suggested in 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 IO is not responsive to thread interruption whne java.net.Socket
is being used.
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();
}
}
|
...
This compliant solution closes the socket connection, by having the shutdown()
method close the socket. As a result, the thread is bound to stop because of a SocketException
. Note that there is no way to keep the connection alive if the thread is to be cleanly halted immediately.
Code Block | ||
---|---|---|
| ||
public final class SocketReader implements Runnable {
// ...
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();
Thread thread = new Thread(reader);
thread.start();
Thread.sleep(1000);
reader.shutdown();
}
}
|
A boolean
flag can be used (as described earlier) if additional clean-up operations need to be performed. When performing asynchronous I/OIO, a java.nio.channels.Selector
may also be brought out of the blocked state by either invoking its close()
or wakeup()
method.
...
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 , for instance, while 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 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));
}
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 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 | ||
---|---|---|
| ||
public final class DBConnector implements Runnable { final String query; DBConnector(String query) { this.query = query; } public void run() { Connection conconnection; try { // Username and password are hard coded for brevity conconnection = DriverManager.getConnection("jdbc:driver:name", "username", "password"); Statement stmt = conconnection.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 that calls initialValue()
obtains a unique connection instance. The advantage of this approach is that a shutdownConnection()
method can be provided so that clients external to the class can also close the connection when the corresponding thread is blocked, or is performing some time consuming activity.
Code Block | ||
---|---|---|
| ||
public final class DBConnector implements Runnable { 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(); } } |
...