img
. .
merely wanted the thread to quit what it was doing and start doing something else, you can do that.
(This is rather nicer than POSIX cancellation, as you may choose to do other things upon
interruption.)
Progressive Shutdown
There are those who suggest that a progressive shutdown scheme is more appropriate than
cancellation. By progressive, they mean first set a flag and wait. If that doesn't do the trick, reduce
the scheduling priority. If that's not enough, restrict permissions and hope the target thread hits a
security violation. Then try interrupt(), then try stop(), then try destroy(). This just
doesn't seem like a terribly great idea.
interrupt()
Basically, a call to interrupt() sets a flag and looks to see if the target thread is blocked. If it
is blocked, it is forcibly awakened. When it sees the flag, it throws an exception. You may also
test to see if a thread has been interrupted via Thread.interrupted() (for the current thread,
this also resets the interrupted flag) or thread.isInterrupted() (for an arbitrary thread, this
does not reset the flag). Once the flag is cleared, no method will throw
InterruptedException until interrupt() is called again (Code Example 9-2). Catching
the exception will also reset the flag.[2]
[2]
This "interrupt flag" was not part of the Java 1.1 specification per se, nor was its behavior with
respect to being cleared well defined. But it is defined in Java 2 and this is how it works in both 1.1
and 2.
Example 9-2 Using thread.interrupt()
Thread 1
Thread 2
try {
t1.interrupt()
... lots of work ...
if (t1.isInterrupted()) {
while (!ready()) {wait();}
System.println(t1 + "int'd")
... more work ...
if (Thread.interrupted() {
exit threaAd or whatever
}
} catch (InterruptedException e)
{
exit thread or whatever
}
In POSIX deferred cancellation and in Java interruption, a thread may run for an arbitrary amount
of time after a cancellation (interruption) has been issued, thus allowing critical sections to
execute without having to disable/enable cancellation. This is good because you know that the
thread will exit synchronously. This is bad because you must do extra work if you wish to ensure
bounded cancellation times. An interrupted thread could go off and run in a loop for hours before
hitting an interruption point. Of course, this might be OK.
There is no pat answer to these issues, and you, as the responsible programmer, must resolve them
on a program-by-program basis. In POSIX you may select asynchronous for one program,
deferred for a second, and a mixture of both for a third. Java does not officially give you this
option because the method stop() has been officially deprecated in JDK 1.2. But as stop()
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home