Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java concurrency guidelines.pdf
Скачиваний:
16
Добавлен:
23.05.2015
Размер:
1.35 Mб
Скачать

THI06-J

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();

}

}

After the shutdown() method is called from main(), the finally block in readData() executes and calls shutdown() again, closing the socket for a second time. However, this second call has no effect if the socket has already been closed.

When performing asynchronous I/O, a java.nio.channels.Selector may also be brought out of the blocked state by invoking either its close() or wakeup() method.

A boolean flag can be used 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 exit cleanly from the while loop.

4.7.4Compliant Solution (Interruptible Channel)

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.

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);

CMU/SEI-2010-TR-015 | 116

THI06-J

// ...

}

}

} 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 technique interrupts the current thread. However, it only stops the thread because the code polls the thread’s interrupted status with the Thread.interrupted() method and terminates 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 being a blocking operation. Similarly, invoking the interrupt() method of a thread that is blocked because of java.nio.channels.Selector also causes that thread to awaken.

4.7.5Noncompliant Code Example (Database Connection)

This noncompliant code example shows a thread-safe DBConnector class that creates one Java Database Connectivity (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 not meant to be shared by multiple threads.

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);

CMU/SEI-2010-TR-015 | 117

THI06-J

//...

}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();

}

}

Database connections, like sockets, are not inherently interruptible. Consequently, this design does not permit a client to cancel a task by closing the resource if the corresponding thread is blocked on a long-running query such as a join.

4.7.6Compliant Solution (Statement.cancel())

This compliant solution uses a ThreadLocal wrapper around the connection so that a thread calling the initialValue() method obtains a unique connection instance. The advantage of this approach is that a cancelStatement() method can be provided so that other threads or clients can interrupt a long-running query when required. The cancelStatement() method invokes the Statement.cancel()method.

public final class DBConnector implements Runnable { private final String query;

private volatile Statement stmt;

DBConnector(String query) { this.query = query;

if (getConnection() != null) { try {

stmt = getConnection().createStatement();

}catch (SQLException e) { // Forward to handler

}

}

}

private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {

Connection connection = null;

@Override public Connection initialValue() { try {

CMU/SEI-2010-TR-015 | 118

THI06-J

// ...

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 statement if (stmt != null) {

try { stmt.cancel();

return true;

} catch (SQLException e) { // Forward to handler

}

}

return false;

}

@Override public void run() { try {

if(stmt == null || (stmt.getConnection() != getConnection())) { throw new IllegalStateException();

}

ResultSet rs = stmt.executeQuery(query);

//...

}catch (SQLException e) {

//Forward to handler

}

// ...

}

CMU/SEI-2010-TR-015 | 119

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]