Mario Navarro Claras
Mario Navarro Claras

Reputation: 65

Stop a Thread that waits for a long period

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?

It have to do this: enter image description here

Upvotes: 0

Views: 247

Answers (1)

user207421
user207421

Reputation: 310909

Just set a socket timeout on the ServerSocket via setSoTimeout(), and catch SocketTimeoutExceptionwhen it fires. You can then inspect your running flag in the catch block etc. and decide whether to continue or stop accepting.

Upvotes: 1

Related Questions