Reputation: 65
I'm having problems to terminate a thread that waits on accept()
call.
accept()
: Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.
I have GestorBuzon
which implements the Runnable
interface:
public class GestorBuzon implements Runnable{
private static volatile boolean running = true;
public void run() {
try {
while (running) {
-- pre code
accept();
-- post code
}
} catch(IOException e) {
terminate();
}
}
public static void terminate() {
running = false;
}
}
And I have MessageSystem
class which starts and stops the thread:
public class MessageSystem {
private GestorBuzon gestorBuzon;
private Thread thread;
public MessageSystem() {
// Starts the Thread
contextInitialized();
}
private void contextInitialized() {
gestorBuzon = new GestorBuzon();
thread = new Thread(gestorBuzon);
thread.start();
}
private void contextDestroyed() {
if (thread != null) {
gestorBuzon.terminate();
try {
thread.join();
} catch (InterruptedException e) {
gestorBuzon.terminate();
}
}
}
}
I call the accept()
function in Runnable
class multiple times, but when I use contextDestroyed()
function, the Thread is still waiting on accept()
and the Thread doesn't terminate. What am I doing wrong?
Upvotes: 0
Views: 247
Reputation: 310909
Just set a socket timeout on the ServerSocket
via setSoTimeout()
, and catch SocketTimeoutException
when it fires. You can then inspect your running
flag in the catch
block etc. and decide whether to continue or stop accepting.
Upvotes: 1