I am running a server and spawning multiple threads to allow for multiple sockets. Obviously, I want to be able to close all sockets on command. I wrote a start and a stop function for my server and it works near instantly unless I run it on Windows.
Start/Stop
public void startServer(int port, int maxThreads, int timeout) throws IOException {
fileServer = new ServerSocket();
fileServer.setPerformancePreferences(1, 0, 1);
fileServer.bind(new InetSocketAddress(port));
for (int threads = 0; threads < maxThreads; threads++) {
sockets.add(new Thread(new ServerInit(fileServer, timeout)));
System.out.println("Socket " + threads + " initialized...");
}
for (int socket = 0; socket < sockets.size(); socket++) {
(sockets.get(socket)).start();
System.out.println("Socket " + socket + " started!");
}
}
public void stopServer() {
if (fileServer.isBound()) {
for (int thread = 0; thread < sockets.size(); thread++) {
sockets.get(thread).interrupt();
}
for (int thread = 0; thread < sockets.size(); thread++) {
try {
sockets.get(thread).join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ServerInit
class ServerInit implements Runnable {
private ServerSocket server;
private int timeout;
public void run() {
while (!Thread.interrupted()) {
try {
server.setSoTimeout(1000);
Socket client = server.accept();
client.setSoTimeout(timeout);
processRequest(receiveRequest(client), client);
client.close();
} catch (SocketTimeoutException ste) {
} catch (IOException io) {
io.printStackTrace();
}
}
System.out.println("Socket closed");
}
}
The issue is that each thread individually takes one second to stop because of the blocking timeout, however, this only occurs on Windows. Why is Windows behaving so differently and how should I go about resolving this issue?
EDIT
Each socket has a one second timeout. I realize that by doing this it causes each socket to take one second to timeout and therefore close, but why is Windows taking one second for each joined thread instead of taking one second total?