Blocking in terms of java.io/java.nio

706 views Asked by At

I just read ...

Classes that work with streams are located in two packages: java.io and java.nio. Classes from the former implement blocking of input/output (I/O): When bytes are being read/written by a process, they become unavailable for other threads of execution. The latter package offers non-blocking I/O with improved performance.

... and would like to understand this a bit more. Does blocking only impact the single relevant thread, but leave the source (i.e. file or database) itself unblocked, ready to be accessed by other streams? Or does the blocking actually prevent the source from being accessed itself, until the current thread is done with the reading?

3

There are 3 answers

2
Grateful On BEST ANSWER

Blocking basically refers to when a thread invokes a read() or write(), it is blocked from doing anything else until there is some data to read or the data is written. The thread can do NOTHING else in the meantime.

So blocking is to do with the thread itself, not the data source.

1
user207421 On

'Blocking' means that the I/O method you are calling blocks the calling thread until at least some data has been transferred, or until an accept or connect operation has either succeede or failed.

'Non-blocking' means that if no data can be transferred, the I/O method returns immediately with an appropriate return value or exception, or that a connect operation proceeds in the background and can be checked for completion later.

For completeness, 'asynchronous' means that the I/O method returns immediately but the operation continues in the background, with its result available via another call in due course, or a callback.

3
Kushal On

Consider a situation where you have 2 threads. Both threads are reading from single socket streams. Here we are concerned about the source bytes which we are reading as well as we need to check in terms of Multi-threading. The reason is due to Blocking I/O

  • Blocking I/O: This is I/O which waits indefinitely for availability of source. The execution of thread waits at that point and it increases chances of Hang or Slowness of your application. java.io package is example of this type

  • Non-Blocking I/O: This is I/O which will not wait for source for infinite time, but will return immediately. java.nio package is example of this type