...
Code Block |
---|
|
public class Container implements Runnable {
private final Vector<Integer> vector = new Vector<Integer>();
public Vector<Integer> getVector() {
return vector;
}
public synchronized void run() {
Random number = new Random(123L);
int i = 10;
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();
}
}
|
Wiki Markup |
---|
This method interrupts the current thread, however, it only stops the thread because the thread logic polls |
the interrupted flag using the method Thread.interrupted()
, and shuts down when it is interrupted the interrupted flag using the method {{Thread.interrupted()}}, and shuts down when it is interrupted. No guarantees are provided by the JVM on when the interruption will be detected by blocking methods such as {{Thread.sleep()}} and {{Object.wait()}} \[[Goetz 06|AA. Java References#Goetz 06]\]. Upon receiving the interruption, the interrupted status of the thread is cleared and an {{InterruptedException}} is thrown. Note that a thread should not be interrupted unless its interruption policy is known in advance. Failure to follow this advice can result in the corruption of mutable shared state. |
Compliant Solution (RuntimePermission stopThread
)
...
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Class Thread, method {{stop}}
\[[Darwin 04|AA. Java References#Darwin 04]\] 24.3 Stopping a Thread
\[[JDK7 08|AA. Java References#JDK7 08]\] Concurrency Utilities, More information: Java Thread Primitive Deprecation
\[[JPL 06|AA. Java References#JPL 06]\] 14.12.1. Don't stop and 23.3.3. Shutdown Strategies
\[[JavaThreads 04|AA. Java References#JavaThreads 04]\] 2.4 Two Approaches to Stopping a Thread
\[[Goetz 06|AA. Java References#Goetz 06]\] Chapter 7: Cancellation and shutdown |
...
CON12-J. Avoid deadlock by requesting and releasing locks in the same order 11. Concurrency (CON) VOID CON14-J. Ensure atomicity of 64-bit operations