0

I have the following problem:

I am running a server, which establishes a TCP connection with all the clients who connect in a separate Thread spawned by ExecutorService. I have an exit command, which should terminate the server including all the threads spawned by ExecutorService. In each particular Thread related to a client I have a while-loop, where I am waiting for client's input in the condition using the InputStream of the associated socket. I also have a global boolean variable, which indicates if the server is online. As soon as it turns to false, I break the loop and terminate the thread. It looks basically like this:

// userInput - String
// in - BufferedReader associated with the input stream of the client's socket
while ((userInput = in.readLine()) != null && serverIsOnline) { 
     //do some stuff
}

However, the problem is that in.readLine() is a blocking operation and therefore the whole server won't be terminated unless all the clients type in something. ExecutorService.shutDownNow() also would not work, as the interrupt is ineffective in this case, because the thread is blocked by another operation. I also want to avoid System.exit(). Any efficient solutions?

Ivaylo Toskov
  • 3,911
  • 3
  • 32
  • 48

1 Answers1

1

Try to close all client sockets. All reading threads should throw IOException in this case.

Denis Borovikov
  • 737
  • 5
  • 9
  • How should I do this? I don't keep track of the sockets used. They are created within the spawned thread for the respective client, therefore I have no access to it. – Ivaylo Toskov Nov 13 '14 at 19:20
  • Yes, you should track all sockets. You can do it by passing sockets to some shared holder object. I.e. `Socket s = ...; holder.add(s)` – Denis Borovikov Nov 13 '14 at 19:24
  • I don't think this is the best workaround for this problem, but it worked, so I will accept your answer. – Ivaylo Toskov Nov 13 '14 at 19:34