Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous IO in Java?

What options for async io (socket-based) are there in java other then java.nio? Also does java.nio use threads in the backround (as I think .NET's async-socket-library does, maybe it's been changed) or is it "true" async io using a proper select call?

like image 424
thr Avatar asked Feb 26 '09 20:02

thr


People also ask

What is asynchronous IO?

In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the transmission has finished.

What is asynchronous Java?

Asynchronous programming in Java is a technique for parallel programming that lets teams distribute work and build application features separately from the primary application thread. Then, when the team is ready with the feature, the code is synced with the main thread.

What is synchronous and asynchronous in Java?

Synchronous vs Asynchronous The main difference between the two is when using synchronous programming we can execute one task at a time, but when using asynchronous programming we can execute multiple tasks at the same time.

Is Java blocking or nonblocking?

Java IO is a blocking IO. This means that if a thread is invoking a read() or write() operation, that thread is blocked until there is some data to read or the data is fully written. That's why it is synchronous IO or blocking IO. Unlike Java IO, Java NIO is a non-blocking IO.


1 Answers

Java's NIO package (as of Java6), provides support for non-blocking I/O only, via Selectors. Java7 is hopefully going to ship with NIO.2, which includes asynchronous I/O support. Today, your best bet is to make use of a framework. ARMistice mentioned Mina. Here are some others.

  1. Grizzly. This is the I/O core for Sun's GlassFish server. Grizzly provides a facility for doing asynchronous reads/writes (via a queue model). It supports TCP and UDP alike. I've used Grizzly in a couple of projects. There are things I like and dislike about the framework, but to detail this is really another topic. I will say that it's quite easy to get something up and running and Grizzly does a lot of the heavy lifting for you.
  2. Netty. This project comes from one of the original authors of the Mina project. I haven't used this one so I don't know about its support for asynchronous I/O. You should take a look.

Now, with regard to your question about threads, NIO Selectors do not use threads for non-blocking I/O. In JDK6 they use select() under Windows and the epoll facility on newer Linux kernels. For asynchronous I/O, threading details depend on the framework.

like image 126
JLR Avatar answered Oct 13 '22 13:10

JLR