I have written a small client server application. The clients connect to the server via a socket. The server creates a new thread for each client connected, and keeps the PrintWriter reference in a Map.
Basically, the server reads data from a data source, performs some checks and writes results to connected clients and the client application formats the data a little and displays in a UI.
Because there were some badly scoped variables on the client application, after running for a while, it used to throw an OutOfMemoryError. This used to make the reader thread on the socket not read all the messages from the socket. But on the server side, the server tries to write as the data comes in to the clients iterating the collection. Since, println() is synchronized on the OutputStream that's passed in while creating PrintWriter the messages try to acquire a lock, eventually bringing the server down. I am creating outputstream like this
The only thread that runs during this time is a Timer thread that at a fixed interval lists all the connected clients by iterating the collection. A core dump would reveal a lot of the following
With the help of a Profiler, I was able to locate those badly scoped variables, and fixed them. The OutOfMemoryErrors have gone now. The client application runs in a stable manner so far.
I should be able to test the server with this new clients soon, But the server design is very bad as well, one bad client brings the whole system down.
Could you please share your ideas thoughts on how can I improve the server to decouple writing the results to clients?
I spent some efforts on the server application and have now modified to fire the results as events and the OutputWriter thread will have a buffer (LinkedList) and keeps writing to the clients one message after other as long as there are messages in the list, sleeping when the list is empty. With this approach also, I would probably not know if the outputStream is not corrupt ( because of some exceptions on client side like OutOfMemory) that donot result in a disconnection.
I am invoking setKeepAlive(true); on both client and server side socket. Any ideas and or suggestions are greatly appreciated.
Thanks very much for your attention, hope I was expressing my problem correctly.