how to kill a thread which is waiting for blocking function call in Java?

anupsth picture anupsth · Aug 6, 2010 · Viewed 15.1k times · Source

I have a thread:

Thread t = new Thread(){
    public void run(){
        ServerSocketConnection scn = (ServerSocketConnection)
                Connector.open("socket://:1234");
        // Wait for a connection.
        SocketConnection sc = (SocketConnection) scn.acceptAndOpen();
       //do other operation
    }
};
t.start();

Lets say no client is connecting to the Server, so this thread will be blocked.Now I want to kill the above thread t? How can I kill it?

Answer

Tom Crockett picture Tom Crockett · Aug 6, 2010

Thread.interrupt() will not interrupt a thread blocked on a socket. You can try to call Thread.stop() or Thread.destroy(), but these methods are deprecated (edit: actually, absent in J2ME) and in some cases non-functional, for reasons you can read about here. As that article mentions, the best solution in your case is to close the socket that you're blocking on:

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.