Java asynchronous IO and java asynchronous io

Source: Internet
Author: User

Java asynchronous IO and java asynchronous io

The key points of the new asynchronous functions are some subsets of the Channel class. The Channel needs to be switched to a background process when processing IO operations. You can use this function to access large, time-consuming operations or other similar instances.
Here, we will only explain the AsynchronousFileChannel for file IO operations separately, but note that there are some other asynchronous pipelines. This includes:

  • AsynchronousFileChannel: for files;
  • AsynchronousSocketChannel: socket for the client;
  • AsynchronousServerSocketChannel: An asynchronous socket for the server to receive incoming connections.

There are two different ways to interact with asynchronous pipelines,

Future-style asynchronous operations

Here, you need to use the Future interface, which can be considered as an ongoing task or an unfinished task. It has two key methods:

IsDone ()
Returns a Boolean value indicating whether the task has been completed.
Get ()
Returned results. If the task is completed, return immediately. Otherwise, it is blocked until it is completed.
Let's take a look at the asynchronous operation of reading a file with a large content, which may exceed MB:

    try(AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("input.txt"))) {            ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 100);            Future<Integer> result = channel.read(buffer, 0);                        while(!result.isDone()) {                // do some other useful work                System.out.println("reading file, I can do other work.");            }             System.out.println("Bytes read: " + result.get());        } catch (IOException | InterruptedException | ExecutionException e) {            e.printStackTrace();        }
Callback-style asynchronous operations

The callback-based Asynchronous Operation requires the help of CompletionHandler. It defines two methods, completed () and failed (), to indicate whether the callback is completed and failed after the callback is completed.
This style is especially suitable for events that you want to know immediately in asynchronous IO operations. For example, if there are a large number of I O operations in the cloud, but the failure of any single operation is not necessarily fatal. Let's look at the example.

        byte[] data = { 2, 3, 5, 7, 11, 13, 17, 19, 23 };        ByteBuffer buffer = ByteBuffer.wrap(data);        CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {            @Override            public void completed(Integer result, Object attachment) { // success                System.out.println("Bytes written: " + result);            }            @Override            public void failed(Throwable exc, Object attachment) { // failed                System.out.println("Asynch write failed: " + exc.getMessage());            }        };        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("primes.txt"),                StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {            channel.write(buffer, 0, null, handler);                        Thread.sleep(10000); // Needed so we don't exit too quickly        } catch (IOException | InterruptedException e) {            e.printStackTrace();        }        

AsynchronousFileChannel is connected to the background thread pool. When the initial thread processes other tasks, I/O operations can be performed.
By default, this is actually the management of a thread pool provided by the runtime environment. If necessary, you can use the application (by reloading AsynchronousFileChannel. open () method) to create a custom thread pool, but this is usually not necessary.
In addition, nio also supports multiple IO, so that a single thread can manage multiple IO pipelines and check which IO pipelines are ready for reading and writing, some classes that support this operation are in java. nio. under the channels package, including SelectableChannel and Selector.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.