Answer the question
In order to leave comments, you need to log in
How to terminate a thread that is in an infinite serverSocket.accept() loop?
For informational purposes, I am writing a TCP / IP server using old Java I / O libraries (synchronous approach, blocking API with a bunch of threads).
One of my threads is responsible for waiting and registering new clients. In fact, most of the time it sits in the accept() method of the server socket. In the main() method / thread, I have implemented server management through cmd commands. The problem is that when you call the "/stop" command, which should close all data streams, client sockets, servers and STREAMS, the stream that sits in the accept () method does not exit and because of it the program continues its execution.
To close the thread, I used all available (including obsolete) methods of the Thread class. I came up with the idea to use System.exit (), but after reading on the forums about this "method of terminating threads" I came across different views on this matter. In practice, this is the only method I have found that terminates the program when the "/stop" command is entered.
What is your opinion? Are there adequate ways to end such a thread, or is it better not to use this blocking API for the server at all?
Answer the question
In order to leave comments, you need to log in
If you are specifically interested in how to interrupt ServerSocket.accept(), then, in theory, close() from another thread causes a SocketException in the accept() method.
There is another option (probably a little more correct) to set setSoTimeout() during initialization and call accept() in the loop, catching SocketTimeoutException. In the catch block, checking some volatile boolean variable is a sign of whether the thread needs to be stopped. Then to stop the server thread just change this variable and the thread itself stops.
An even more correct way is to use nio, preferably using some library like netty.
A thread must manage its own life cycle. You can only send signals to it via a shared volatile variable or some kind of synchronization primitive.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question