1

Please help me to understand the disadvantage of Thread-Pool pattern using NIO.

I found this Question: Java NIO non-blocking mode vs node.js asychronous operation but it do not answer how NIO affects scheduling behaviour in java.

How I understand Node.js and java.IO:

Node.js uses Event loop and non-blocking IO combined with callbacks. This allows to process other tasks while IO-call not finished like this:

Event loop in node.js

Using old java.IO library and thread pool pattern the java thread get blocked till IO operation is completed. In the meantime the thread can not process other tasks and barred from scheduling.

But now. What about NIO? Consider we have a thread pool with max 10 threads. Every thread get some job as Runnable object.

So what will happen if a long-term IO operation is required. I can't believe that the current undone Runnable will be replaced by other till the initial IO call is completed.

So how exactly changes java.NIO the scheduling behaviour in Java by comparison with java.IO ?

Community
  • 1
  • 1
alex
  • 8,904
  • 6
  • 49
  • 75
  • Node.js uses `libuv` library for the asyn IO, and I can assure you libuv uses a thread pool. – David Haim Sep 03 '15 at 11:05
  • @DavidHaim Yes I know. I just want to know how the scheduling works with java.NIO. Get the thread blocked or not. – alex Sep 03 '15 at 11:12

1 Answers1

3

In essence, NIO provides the means to program your own single-threaded event-loop similar to node.js. Java IO, in comparison, provided no such means.

Implementations could differ, but in essence, you could create a thread which reads from Selector and executes some registered callbacks for each successful select. Then, for each new kind of IO, you could register it's Channel (or anything) with same Selector, and in this way implement 100% the same (but much more Flexible) implementation of single-threaded callback event loop. By itself, NIO does not provide such event loop or anything similar, if that's what you are asking.

It's worth to notice, that the implementation behind NIO differs depending on infrastructure underneath. For example writing to file using NIO in POSIX systems would translate to native OS calls, while running it one some blocking-IO-only-OS would make Java create a separate thread for each IO for backward compatibility (as there would technically be no other way to do NIO).

I hope that answers your question, which was a bit blurry.

user207421
  • 305,947
  • 44
  • 307
  • 483
bezmax
  • 25,562
  • 10
  • 53
  • 84