MC Emperor
MC Emperor

Reputation: 22997

Interrupting thread which is blocked waiting on IO from socket?

I have an app that listens to incoming connections on a specified hostname and port. The listening is invoked with the method listen() (see below), which waits constantly for an incoming connection using ServerSocket.accept(), creating a new Thread to handle the input stream.

private ServerSocket serverSocket;
private Thread listenerThread;

public void listen() throws IOException {
    this.listenerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                try {
                    Socket socket = TheServerClass.this.serverSocket.accept();
                    // Create new thread to handle the incoming connection
                }
                catch (IOException exc) { }
            }
        }
    });
    this.listenerThread.start();
}

Now I want to stop the running of listenerThread. But when I call this.listenerThread.interrupt(), this doesn't work.
I thought you can stop a thread by interrupting it, so why isn't that working?

(Notice: A possible solution is to close the ServerSocket using this.serverSocket.close(), but can it be accomplished with interrupt() or something?)

Upvotes: 1

Views: 2069

Answers (3)

xyz
xyz

Reputation: 201

Use this:

public class MyThread extends Thread {

    private boolean stop;
    private ServerSocket serverSocket;

    public MyThread(ServerSocket ss) {
        this.serverSocket = ss;
        this.stop = false;
    }

    public void setStop() {
        this.stop = true;
        if (this.ss != null) {
            this.ss.close();
        }
    }

    public void run() {
        while (!stop) {
            try {
                Socket socket = serverSocket.accept();
                // Create new thread to handle the incoming connection 
            }
            catch (IOException exc) { }
        }
    }
}

and from the listen() method just call setStop() method of the thread.

Upvotes: 0

polve
polve

Reputation: 3138

Call serverSocket.close(),

I guess since you are not doing IO yet - you can not interrupt it, and since the accept() doesn't throw InterruptedException you won't be able to interrupt it. The thread is interrupted, but that flag you have to check for yourself Thread.isInterrupted().

See How can I interrupt a ServerSocket accept() method?.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691755

The answer is in the question. You need to close the socket. It's done using serverSocket.close(). Thread.interrupt() doesn't care about sockets.

Upvotes: 1

Related Questions