AsynchronousFileChannel in Java NIO
Java.nio package was introduced in the version java 1.4 edition. It allows us to deal with different channels concurrently because it supports concurrency and multi-threading. The asynchronous file channel API is responsible for the java NIO package and it is defined under the NIO channels package. In order to import the AsynchronousFileChannel API to our program follow the below syntax as follows:
Asynchronous channels are safe for use by multiple concurrent threads because this channel enables file operations to execute asynchronously unlike synchronous I/O operations in which a thread enters into action and waits until the request is completed. This is the only difference between the asynchronousFileChannel and NIO’s FileChannel.
The request is first passed by the threads to the kernel of the operating system to get it done while the thread continues to another job. After the job of the kernel is done, it signals the thread, then the thread acknowledges the signal and interrupts the current job and processes the I/O job as needed in asynchronous channels.
There are two approaches for achieving concurrency and these are as listed below. We will see the above two approaches in detail with the examples.
- Future Object
- Completion Handler
Approach 1: Future Object
It returns a java.util.concurrent.Future object. There are two useful methods to retrieve information and these two methods are –
- get() method: It returns the status of the operation that is handled asynchronously on the basis of which further execution of other tasks could get decided.
- isDone() method: This method will check whether the task is completed or not.
Approach 2: Completion handler
For this approach, we are going to use the CompletionHandler interface and It consists of two useful methods that we are going to override. In this, a completion handler is created for consuming the result of an asynchronous I/O operation as once a task is completed then only the handler has functions that are executed.
These two methods are as follows:
- completed() method: This method is invoked when the I/O operation completes successfully.
- failed() method: This method is invoked if the I/O operations fail.