• Post Reply Bookmark Topic Watch Topic
  • New Topic

CPU consumption of blocking SocketInputStream.read()

 
Florin Bratu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone!

I have some odd experiences with the read() method of an java.io.InputStream attached to a blocking socket. The implementation I'm using is the default Sun's java.net.SocketInputStream. According to the javadoc of java.io.InputStream#read(byte[], int, int), the read() method will block until input data is available. But what exactly does "block" mean? Will this "block" consume any CPU? I am asking because I have developped an application which connects to a server and sits forever in a loop, in a separate thread, calling InputStream.read() and doing something with the result. Now, I have run this application in two scenarios:
1) Connect it to a server which constantly writes something on the remote endpoint; in this case, the read() method very often does not block
2) Connect it to a "phony" server - I use Linux so I start one using netcat, something like nc -l $random_port. In this case, the thread which calls read() is forever "blocked"

Now, I have run a profiler against both executions. According to the profiler results, the CPU spends more time in the InputStream.read() method in the second case than in the first! This goes totally against my intuition about how SocketInputStream.read() is implemented.

Is there someone who had some similar experience, or who can provide some insight on what is going on "under the hood" when calling SocketInputStream.read() ?

Thanks,
Florin.
 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That seems perfectly reasonable to me. If you go into the bakery and buy a loaf of bread, you usually won't spend much time in the bakery. But if they don't have any bread and you have to wait for them to bake some more, you're going to spend more time in the bakery.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!