Java Reference
In-Depth Information
Future
<
Integer
>
result
=
channel
.
read
(
buffer
,
0
);
while
(!
result
.
isDone
())
{
// Do some other useful work....
}
System
.
out
.
println
(
"Bytes read: "
+
result
.
get
());
}
Callback-Based Style
The callback style for asynchronous I/O is based on a
CompletionHandler
, which
defines two methods,
completed()
and
failed()
, that will be called back when the
operation either succeeds or fails.
This style is useful if you want immediate notification of events in asynchronous
I/O—for example, if there are a large number of I/O operations in flight, but failure
of any single operation is not necessarily fatal:
byte
[]
data
=
{
2
,
3
,
5
,
7
,
11
,
13
,
17
,
19
,
23
};
ByteBuffer
buffy
=
ByteBuffer
.
wrap
(
data
);
CompletionHandler
<
Integer
,
Object
>
h
=
new
CompletionHandler
()
{
public
void
completed
(
Integer
written
,
Object
o
)
{
System
.
out
.
println
(
"Bytes written: "
+
written
);
}
public
void
failed
(
Throwable
x
,
Object
o
)
{
System
.
out
.
println
(
"Asynch write failed: "
+
x
.
getMessage
());
}
};
try
(
AsynchronousFileChannel
channel
=
AsynchronousFileChannel
.
open
(
Paths
.
get
(
"primes.txt"
),
StandardOpenOption
.
CREATE
,
StandardOpenOption
.
WRITE
))
{
channel
.
write
(
buffy
,
0
,
null
,
h
);
Thread
.
sleep
(
1000
);
// Needed so we don't exit too quickly
}
The
AsynchronousFileChannel
object is associated with a background thread pool,
so that the I/O operation proceeds, while the original thread can get on with other
tasks.
By default, this uses a managed thread pool that is provided by the runtime. If
required, it can be created to use a thread pool that is managed by the application
(via an overloaded form of
AsynchronousFileChannel.open()
), but this is not
often necessary.
Finally, for completeness, let's touch upon NIO's support for multiplexed I/O. This
enables a single thread to manage multiple channels and to examine those channels