Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 752
anupsth Avatar asked Aug 06 '10 06:08

anupsth


People also ask

Can you interrupt a blocked thread?

Whether a thread is interrupted can be checked by the isInterrupted() method of Thread class. Another method, Thread. interrupted() returns the interrupt status and also clears it. A thread which is blocked to acquire an intrinsic lock (BLOCKED state) cannot be interrupted.

How do you kill a specific thread in Java?

Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.

How do you kill a waiting thread?

interrupt() If any thread is in sleeping or waiting for the state then using interrupt() method, we can interrupt the execution of that thread by showing InterruptedException . A thread that is in the sleeping or waiting state can be interrupted with the help of interrupt() method of Thread class.


1 Answers

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.

like image 83
Tom Crockett Avatar answered Sep 28 '22 04:09

Tom Crockett