Search code examples
javacpublockdatainputstream

Java DataInputStream.read() causing 20% constant CPU usage while being blocked.


I have a server-side application opens a socket thread for each connected client. I have a DataInputStream in each thread, which calls read(byte[]array) to read data. I also set the socket timeout to a few minutes. The main code is something like this:

while (dataInputStream.read(array) != -1) { do something... }

However, after several hours running, in jconsole with topthreads plugin, I can see several client threads use 20%ish CPU each. If I click on it, the call stack shows the thread is blocked on the above line, on the read() function.

I know read() function will normally block to wait for data. When blocked, it consumes little CPU cycles. Now it's using 20%ish each and my server is running more and more slower when more threads have the same problem. My server has about 5 connection requests per second, and this happens really rarely as in several hours only 5 threads have the problem.

I am really confused. Can someone help me?


Solution

  • when jvm is waiting to read data from a socket there is a lot more activities the system needs to constantly do..

    I don't have the exact technique used but this link should give some idea..

    why don't you try using a BufferedInputStream or any of the StreamReaders .. these classes would help in the performance.

    you could try using classes from java.util.concurrent package to improve thread handling (creating a thread pool would help in reducing the total memory consumed, thereby helping in the overall system performance).. not sure if you are doing this already