Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

blocking SocketInputStream.read() CPU consumption

843790Oct 31 2009 — edited Nov 3 2009
Hello everyone!

I have some odd experiences with the read() method of an InputStream attached to a blocking socket. The implementation I'm using is the default Sun's java.net.SocketInputStream. According to the javadoc of InputStream.read(), the 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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 1 2009
Added on Oct 31 2009
3 comments
1,713 views