Java Reference
In-Depth Information
mbf
.
position
(
0
);
mbf
.
put
(
b
);
// Zeros the file
}
Even with buffers, there are limitations of what can be done in Java for large (e.g.,
transferring 10G between filesystems) I/O operations that perform synchronously
on a single thread. Before Java 7, these types of operations would typically be done
by writing custom multithreaded code, and managing a separate thread for per‐
forming a background copy. Let's move on to look at the new asynchronous I/O fea‐
tures that were added with JDK 7.
g
d
O
e
Async I/O
The key to the new asynchronous functionality are some new subclasses of
Channel
that can deal with I/O operations that need to be handed off to a background
thread. The same functionality can be applied to large, long-running operations,
and to several other use cases.
In this section, we'll deal exclusively with
AsynchronousFileChannel
for file I/O,
but there are a couple of other asynchronous channels to be aware of. We'll deal
with asynchronous sockets at the end of the chapter. We'll look at:
•
AsynchronousFileChannel
for file I/O
•
AsynchronousSocketChannel
for client socket I/O
•
AsynchronousServerSocketChannel
for asynchronous sockets that accept
incoming connections
There are two different ways to interact with an asynchronous channel—
Future
style, and callback style.
Future-Based Style
We'll meet the
Future
interface in detail in
Chapter 11
, but for the purpose of this
chapter, it can be thought of as an ongoing task that may or may not have completed
yet. It has two key methods:
isDone()
Returns a Boolean indicating whether the task has finished.
get(
Returns the result. If finished, returns immediately. If not finished, blocks until
done.
Let's look at an example of a program that reads a large file (possibly as large as 100
Mb) asynchronously:
try
(
AsynchronousFileChannel
channel
=
AsynchronousFileChannel
.
open
(
Paths
.
get
(
"input.txt"
)))
{
ByteBuffer
buffer
=
ByteBuffer
.
allocateDirect
(
1024
*
1024
*
100
);