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

THI05-J

thread.start();

Thread.sleep(5000);

container.shutdown();

}

}

4.6.3Compliant Solution (Interruptible)

In this compliant solution, the Thread.interrupt() method is called from main() to terminate the thread. Invoking Thread.interrupt() sets an internal interrupt status flag. The thread polls that flag using the Thread.interrupted() method, which returns true if the current thread has been interrupted and clears the interrupt status.

public final class Container implements Runnable {

private final Vector<Integer> vector = new Vector<Integer>(1000);

public Vector<Integer> getVector() { return vector;

}

@Override public synchronized void run() { Random number = new Random(123L);

int i = vector.capacity();

while (!Thread.interrupted() && i > 0) { vector.add(number.nextInt(100));

i--;

}

}

public static void main(String[] args) throws InterruptedException { Container c = new Container();

Thread thread = new Thread(c); thread.start(); Thread.sleep(5000); thread.interrupt();

}

}

A thread may use interruption for performing tasks other than cancellation and shutdown. Consequently, a thread should not be interrupted unless its interruption policy is known in advance. Failure to do so can result in failed interruption requests.

CMU/SEI-2010-TR-015 | 112

THI05-J

4.6.4Compliant Solution (Runtime Permission stopThread)

Removing the default java.lang.RuntimePermission stopThread permission from the security policy file prevents threads from being stopped using the Thread.stop() method. This approach is not recommended for trusted, custom-developed code that uses that method because the existing design presumably depends on the ability of the system to perform this action. Furthermore, the system may not be designed to properly handle the resulting exception. In these cases, it is preferable to implement an alternate design approach corresponding to another compliant solution described in this guideline.

4.6.5Risk Assessment

Forcing a thread to stop can result in inconsistent object state. Critical resources may also leak if clean-up operations are not carried out as required.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

THI05- J

low

probable

medium

P4

L3

4.6.6References

[Arnold 2006]

Section 14.12.1, “Don’t stop”

 

Section 23.3.3, “Shutdown Strategies”

[Darwin 2004]

Section 24.3, “Stopping a Thread”

[Goetz 2006]

Chapter 7, “Cancellation and shutdown”

[Oaks 2004]

Section 2.4, “Two Approaches to Stopping a Thread”

[Sun 2009b]

Class Thread, method stop, interface ExecutorService

[Sun 2008c]

Concurrency Utilities, More information: Java Thread Primitive Deprecation

[Sun 99]

 

CMU/SEI-2010-TR-015 | 113

THI06-J

4.7THI06-J. Ensure that threads and tasks performing blocking operations can be terminated

Threads and tasks that block on operations involving network or file input/output (I/O) must provide callers with an explicit termination mechanism to prevent denial-of-service vulnerabilities.

4.7.1Noncompliant Code Example (Blocking I/O, Volatile Flag)

This noncompliant code example uses a volatile done flag to indicate that it is safe to shut down the thread, as suggested in guideline “THI05-J. Do not use Thread.stop() to terminate threads” on page 110. However, setting the flag does not terminate the thread if it is blocked on network I/O as a consequence of invoking the readLine() method.

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

CMU/SEI-2010-TR-015 | 114

THI06-J

thread.start();

Thread.sleep(1000);

reader.shutdown(); // Shutdown the thread

}

}

4.7.2Noncompliant Code Example (Blocking I/O, Interruptible)

This noncompliant code example is similar to the preceding one but uses thread interruption to shut down the thread. Network I/O is not responsive to thread interruption when a java.net.Socket is being used. The readData() and main() methods are modified as follows:

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

}

}

4.7.3Compliant Solution (Close Socket Connection)

This compliant solution resumes the thread by having the shutdown() method close the socket. The readLine() method throws a SocketException when the socket is closed, which lets the thread proceed. Note that there is no way to keep the connection alive if the thread is to be halted cleanly and immediately.

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 {

CMU/SEI-2010-TR-015 | 115

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