Social Media

Blocking vs Non-blocking IO

IO

  • Streams
  • Blocking
  • Call the thread, and the thread is blocked until the data is read or fully written
[sourcecode lang=”java”] InputStream input = … ; // get the InputStream from the client socket

BufferedReader reader = new BufferedReader(new InputStreamReader(input));

String nameLine = reader.readLine();
[/sourcecode]

NIO

  • Buffer Oriented
  • Non-blocking
  • Call thread and it delegates – only returning when ready to send data
  • Selectors – single thread monitors multiple input channels – register multiple channels with selector and it can select which one to use
[sourcecode lang=”java”] ByteBuffer buffer = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buffer);

while(! bufferFull(bytesRead) ) {
bytesRead = inChannel.read(buffer);
}
[/sourcecode]

References

http://tutorials.jenkov.com/java-nio/nio-vs-io.html#main-differences-between-java-nio-and-io

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment: