1
I have a multithreaded server that sits in an infinite loop waiting for new connections and I want to be able to stop this loop when I press Ctrl-C (or something similar). I tried to use that one solution and tried to do something like this:
private void waitForConnections() {
boolean done = false;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
super.run();
System.err.println("Exiting");
done = true;
}
});
while (!done) {
try {
Socket userSocket = this.serverSocket.accept();
// Faz alguma coisa...
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I cannot change the value of the done variable within the thread. How can I solve this problem in the simplest and most elegant way possible?
There is an error because your code will never test the
!done
, because you have awhile(true)
.– lemoce
The problem has been solved?
– Sveen
The question is very interesting, I wanted to answer but I do not know if I will find time. By the way, I believe that
super.run()
is not necessary.– Piovezan
Sveen, Not yet. The error that the lemoce said to fix was a code typing error. The main problem persists!
– Michael Pacheco
Try to set
setSoTimeout()
, then the Accept will release aSocketTimeoutException
, so that the Accept is not blocked endlessly. If this is the solution, it is because Accept keeps blocking the thread endlessly, just when you emit Ctrl-C, your code does not go back to the beginning of the loop and so test the!done
.– lemoce
It does not seem a good solution because the server will be on for hours and it may happen that no client wants to connect. In your solution the server would stop receiving requests after the timeout occurs.
– Michael Pacheco
@Michaelpacheco may be. I gave a solution, but the important thing is why the problem happens.
– lemoce