Java Async File I/O
In this page:
What is Asynchronous File I/O?
Asynchronous file I/O lets a program start a read or write operation and continue doing other work immediately, being notified only once the operation actually completes, instead of blocking the calling thread the entire time.
Example: What is Asynchronous File I/O?
public class Main {
public static void main(String[] args) {
System.out.println("Async I/O starts an operation and continues, notified only on completion");
}
}
Login to try C/C++/Java/PHP code in the editor
AsynchronousFileChannel Basics
AsynchronousFileChannel, part of NIO.2, is opened much like a regular FileChannel but supports non-blocking reads and writes, and like other NIO channels it still reads into and writes from a ByteBuffer.
Example: AsynchronousFileChannel Basics
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("demo", ".txt");
AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
System.out.println("Opened: " + channel.isOpen());
channel.close();
Files.delete(file);
}
}
Login to try C/C++/Java/PHP code in the editor
Reading Asynchronously with a Future
Calling read on an AsynchronousFileChannel returns a Future immediately, and the calling thread can continue running other code, only blocking if and when it later calls get() to retrieve the actual result.
Example: Reading Asynchronously with a Future
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.*;
import java.nio.ByteBuffer;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("demo", ".txt");
Files.writeString(file, "hello");
AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(5);
Future<Integer> future = channel.read(buffer, 0); // returns immediately
future.get(); // blocks only here, when the result is needed
System.out.println(new String(buffer.array()));
channel.close();
Files.delete(file);
}
}
Login to try C/C++/Java/PHP code in the editor
Reading Asynchronously with a CompletionHandler
A CompletionHandler is an alternative to Future that avoids blocking entirely: its completed method is called automatically with the result when the operation succeeds, and its failed method is called if the operation encounters an error.
Example: Reading Asynchronously with a CompletionHandler
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("demo", ".txt");
Files.writeString(file, "data");
AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(4);
channel.read(buffer, 0, null, new CompletionHandler<Integer, Void>() {
public void completed(Integer result, Void attachment) {
System.out.println("Read complete: " + new String(buffer.array()));
}
public void failed(Throwable exc, Void attachment) {
System.out.println("Failed: " + exc.getMessage());
}
});
Thread.sleep(100);
channel.close();
Files.delete(file);
}
}
Login to try C/C++/Java/PHP code in the editor
Writing Asynchronously
Asynchronous writes work the same way as asynchronous reads, returning a Future or accepting a CompletionHandler, and the operation is only considered complete once the data has actually been written to the underlying file.
Example: Writing Asynchronously
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.*;
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("demo", ".txt");
AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.wrap("async write".getBytes());
channel.write(buffer, 0).get(); // complete once actually written
channel.close();
System.out.println(Files.readString(file));
Files.delete(file);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: