indiWiz.com

Subhash's Tech Log

Archive for the ‘concurrent’ tag

Interrupting a Thread in Java

without comments

Long long ago, when I was studying in College, my professors taught me to abruptly interrupt a running Thread using Thread.stop() method. Later this method was deprecated. Then in some article I read to interrupt a running thread, you have to write your custom logic:

class MyThread extends Thread{

    private boolean isCancelled = false;

    public void run(){
        while(isCancelled != true){
            // do long running job
        }
    }

    public void cancel(){
        isCancelled = true;
    }
}

This seems to be a valid code, but there is an issue. If we are doing some blocking operation, or an IO operation inside the loop, then the cancel notification does not reach until that is finished. Well, so how do we solve this issue?

Thread API

The java.lang.Thread class has the following API methods:

void interrupt();
boolean isInterrupted();

To signal a running Thread about our request for termination, we can call its interrupt() method. Unlike the old stop() method, this does not abruptly terminate the execution of the Thread. What is does:

When Thread is in Blocking mode When Thread is in normal execution
Thread’s interrupt status will be cleared, and InterruptedException thrown. Thread’s interrupt status will be set.

A Thread is in blocking mode during following states:

  1. Thread blocked in invocation of wait(...) methods; or
  2. join(...) methods; or
  3. sleep(...) methods.

Now my actual reason for exploring this concept was due to an issue in RESTClient. I had wanted to implement a Stop button just as in a normal browser. So my Thread was not blocked using any of the interruptable methods, but due to a socket IO. So how can I solve this?

class MyThread extends Thread{

    public void run(){
        while(isInterrupted() != true){
            // do socket IO
        }
    }

}

But this has the same limitation as the first code I wrote. If the socket IO is in progress, this condition is not checked until the IO is done. So what finally is the solution? It is simple:

class MyThread extends Thread{

    private Socket soc = ..;

    public void run(){
        // do socket IO
    }

    @Override
    public void interrupt(){
        if(soc != null){
            soc.close(); // wrap in try/catch
        }
        super.interrupt();
    }

}

When we close the Socket object, the IO will fail raising an IOException which we can gracefully handle.

Written by Subhash Chandran

November 18th, 2008 at 8:52 am

Posted in Uncategorized

Tagged with , , ,