A selectable channel is either in blocking mode or in non-blocking mode. In blocking mode, every I/O operation invoked upon the channel will block until it completes. In non-blocking mode an I/O operation will never block and may transfer fewer bytes than were requested or possibly no bytes at all. The blocking mode of a selectable channel may be determined by invoking its isBlocking method.
what does it mean when it says "I/O operation invoked upon the channel will block until it completes"
[Parmeet]: what does it mean when it says "I/O operation invoked upon the channel will block until it completes"
The method will simply pause and not do anything until it can complete - until it has data to return. Other threads will be able to continue working, but the blocking thread will not be able to do anything until it completes.
Let's say you try to read 100 bytes from a socket. In blocking IO method invocation would block until all 100 bytes have been read. In case of non-blocking IO method would return immediately even if it has not read all 100 bytes.
Non-blocking IO means that a read doesn't block, or wait for input. In the example above, the read blocks until it gets some input, not necessarily all 100 bytes. Using non-blocking IO, the read will return immediately even if there's no input to read. Non-blocking is important for applications like servers. If you use blocking IO, you have to create a thread per connection because each thread will block reading the connection. Since there is a finite number of threads an application can spawn, this is not very scalable. With non-blocking IO the application can have a pool of threads which poll connections until there's data to read. Since the number of threads is not directly tied to the number of connections, this application will scale better than the blocking IO version. Here is a more in-depth article on the subject.
[Maris Orbidans]: In case of non-blocking IO method would return immediately even if it has not read all 100 bytes.
[Joe Ess]: Actually, this is the case with the regular IO classes (see our FAQ entry, ReadDoesntDoWhatYouThinkItDoes
I disagree with this last sentence as I understand it. Since I agree with everything else Joe wrote above, I think this is just a minor misunderstanding by one of us. Regular IO classes (non-NIO) always block until at least one byte can be read. The don't necessarily block until all requested bytes have been read, but they do block until at least one byte can be read. That's true for both regular IO classes, and blocking NIO classes, as Joe said above. The part I'm adding is that reguilar IO behaves as blocking IO, not non-blocking IO. [ April 14, 2008: Message edited by: Jim Yingst ]
"I'm not back." - Bill Harding, Twister
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop