In a application that I made, server accepts socket connection from clients and do various work. List of clients is stored in clients which has a LinkedList type.
I am using while statement with conditional statement based on size of the clients queue.
I want to know if there is a way to solve problems described below… so that server will not hang forever.
while(clients.size()>0){ //few clients the queue is alive at the moment
//Suddenly, all clients in the queue shut down at this point in the while loop,
//Another thread, which checks clients knows that clients are dead
//so clients.size() becomes 0, but there is no way to check that at this point
//and server is expecting for connection clients forever
Socket socket= server.accept();
socket.close();
}
//printout results
edit
The clients list is not just existing clients. It is a list of alive clients. This list is gets updated by another thread.
I have while statement above, because I want to do some job after there is no alive clients left. (either finished their job, or just died)
I want to solve this problem without using timeout exception, because clients will response in random time. (again, liveness of clients is checked by another Thread with heartbeat technique)
You can set the timeout on the
ServerSocketand catch theSocketTimeoutException:This way you will check the status of the client list every second or so.
Don’t forget to synchronize access to
clientsif you have other threads accessing it. Either wrap it usingCollections.synchronizedListor put appropriate synchronization in the parts of your code that access the variable.