1

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?

Lee
  • 103
  • 1
  • 11

2 Answers2

1

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

Anantha Sharma
  • 9,920
  • 4
  • 33
  • 35
  • according to [link](http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/) using a bufferedInputStream has same performance as using read(byte[]). – Lee Jul 30 '11 at 20:42
0
while (dataInputStream.read(array) != -1) { do something... }

This code is wrong anyway. You need to store the return value of read() in a variable so you know how many bytes were returned. The rest of your application can't possibly be working reliably without this anyway, so worrying about timing at this stage is most premature.

However unless the array is exceptionally small, I doubt you are really using 20% CPU in here. More likely 20% of elapsed time is spent here. Blocking on a network read doesn't use any CPU.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I removed the irrelevant codes that's why I didn't put the return variable there. Anyway thanks for the answer. – Lee Jul 31 '11 at 07:55