You are on page 1of 1

Concurrency:

-----------Terminating a thread which is blocked:(from Tinking in java, COncurrency, Termin


ating threads section)
---------------------------------------Thread can be blocked due to various resons:
1)sleep
2)wait , until notify/signal
3)calling synchnroized method for which lock is acquired by another thread
4)waiting for IO to complete
To terminate a blocked task, we should call interrupt() on that thread.
This sets the interrupted status
>Such a thread will throw InterruptedException() if it is already blocked or it
attempts a blocking operation
When once this exception is thrown interrupted status will be reset.
>Thread can also learn if it is interrupted by verifying interrupted(). This als
o resets the flag
While using executors, where you cannot directly manipulate threads, you can use
the cancel method on the future object returned by the submit operation.
future.cancel(true);
BUT If a Thread is blocked for reason-3 and reason-4 then you cannot interrupt i
t. But if the IO is of type nio then they can be interrupted.
>using interrupted()
But if we only exit a run() loop, only by throwing exception on a blocking call,
then we will not be always able to leave the run loop.
We want to exit a run() loop even if blocking calls are not made. This is possib
le by checking the interrupted flag.
public void run() {
try {
while(!Thread.interrupted()) {
This also solves the problem partially for non interruptible blocking scenarios,
you can check the status after you have come out of that blocking.

You might also like