In my java application, I have a TCP server which sends data generated in my app to all connected clients. For each new socket, I create a new thread. Following is the thread code.
public void run() {
try {
PrintStream printStream = new PrintStream(socket.getOutputStream(), true);
while (true) {
if (socket.isClosed()) {
break;
}
synchronized (DataSource.getInstance()) {
printStream.println(DataSource.getInstance().getData());
try {
DataSource.getInstance().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Data generating thread writes to DataSoure
when new data is available and calls notifyAll()
so all threads which handles connected sockets wake up and send available data to clients.
My problem is, even if a client disconnected, socket.isClosed()
returns true. So the thread which handles the socket never gets terminated.
Why does this happen? How can I exit the thread when a client gets disconnected?