- The Interrupt Flag
- Thread Interrupt Methods
- Using Thread Interrupts
- Handling Thread Interrupts
- Larger Issues
- The interrupt flag is a per-thread boolean flag.
- If the interrupt flag is true, the thread throws a
Interrupted
Execution
exception.
- When the exception is caught, the associated flag is cleared.
- The exception is thrown only at a interruption point.
-
t.interrupt()
sets t
's interrupt flag to true.
- The current value of
t
's value is ignored.
- If
t
is blocked, it is unblocked.
-
Thread.interrupted()
returns the current thread's interrupt flag.
- Clears the flag it it's set.
- A thread with a cleared flag doesn't throw an interrupt.
-
t.isInterrupted()
returns t
's interrupt flag.
- Threads support asynchronous, thread-to-thread communication.
- So do mutually shared class instances.
- An interrupt can unblock a blocked process.
- So can a suitable prepared shared class instance.
- Interrupts are essential in I-O operations.
- Unfortunately, they are also ill defined and ill behaved.
- the
Interrupted IO Exception
.
- Interrupts allow one-bit communication.
- Shared class instances allow arbitrary communication.
- Convention interprets an interrupt as "cancel execution".
- There are two problems to deal with directly.
- Premature exit from interruptible methods.
- The
Interrupted Execution
exception.
- There are three ways to deal with them.
- Indolence, ignorance, propagation.
- The choice depends on the situation.
- Don't deal with interrupts at all.
- Simple, but usually a bad choice.
- The exception may leave inconsistent state.
- Ignore interrupts.
- Usually simple, but breaks interrupts.
- Unbounded thread execution possible.
- Propagate interrupts.
- Simple initially, but can get complicated.
- Pretending interrupts never happen.
synchronized void down() {
while (count < 1) wait()
count--
}
- The while handles premature exit.
- The interrupt, however, percolates out.
- Ignoring interrupts.
synchronized void down()
while (count < 1)
try { wait() }
catch (InterruptedExecution ignore) { }
- The interrupt has disappeared.
- Propigate interrupts.
synchronized void down()
boolean interrupted = false
while (count < 1)
try { wait() }
catch (InterruptedExecution ignore)
interrupted = true
if (interrupted)
throw new InterruptedExecution()
- Having enough interruption points.
- Interrupts are asynchronous and autonomous.
- Not at all like hardware.
- Interrupts are not stacked.
- Follow-up interrupts can get lost.
- One-to-many works, many-to-one doesn't.
- Interrupts provide asychronous, zero-bit communication between threads.
- Consider other forms first.
- Interrupts can unblock threads, and result in exceptions.
- Good code should handle both.
- Interrupt behavior follows convention.
- Usually premature thread termination.
- Follow convention, but consider interrupt alternatives.
- Shared termination objects.
- Blocking's the problem here.
This page last modified on 8 August 2002.