I've looked all over but I could not find a good example explaining NIO2 or how to do asynchronous IO with Java sockets. For example, if I want to speed up a web crawler by allowing threads to use async IO to read from sockets instead of regular synchronous IO, how would I achieve this?
1 Answer
NIO2 is not faster than synchronous I/O. It allows to run many connections (tens of thousands) with a few threads. If you can afford to spend a thread for each connection, use synchronous I/O - it is simpler to program.
3 Comments
Jin
Sorry for the late reply. Can you clarify when would it be appropriate to use NIO2?
Jin
In other words, when would it be better to have fewer threads with many connections, verses more threads with a connection for each thread?
Alexei Kaigorodov
Threads take a lot of memory, so it is unpractical to have >1000 threads on a computer, and even powerful server machine hardly can bear more than 10000 threads at once. So the memory consumption is the main criteria. I would say that for <100 connections I would definitely use one thread per connection, and for >100 I would think if I can spend so much memory for threads.