eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this article, we are going to explore the foundations of one of the key additional APIs of the new I/O (NIO2) in Java 7- asynchronous channel APIs.

This is first in a series of articles that will cover this particular topic.

The asynchronous channel APIs are an enhancement to the earlier new I/O (NIO) APIs that shipped with Java 1.4. To read about NIO Selectors, please follow this link.

Another enhancement to the NIO APIs is the new File System API. You can read more about its file operations and path operations on this site too.

To use the NIO2 asynchronous channels in our projects, we have to import the java.nio.channels package as the required classes are bundled in it:

import java.nio.channels.*;

2. How Asynchronous Channel APIs Work

The asynchronous channel APIs were introduced into the existing java.nio.channels package, simply put – by prefixing the class names with the word Asynchronous.

Some of the core classes include: AsynchronousSocketChannel, AsynchronousServerSocketChannel and AsynchronousFileChannel.

As you may have noticed, these classes are similar in style to the standard NIO channel APIs.

And, most API operations available to the NIO channel classes are also available in the new asynchronous versions. The main difference is that the new channels enable some operations to be executed asynchronously.

When an operation is initiated, the asynchronous channel APIs provide us with two alternatives for monitoring and controlling the pending operations. The operation can return java.util.concurrent.Future object or we can pass to it a java.nio.channels.CompletionHandler.

3. The Future Approach

A Future object represents a result of an asynchronous computation. Assuming we want to create a server to listen to client connections, we call the static open API on the AsynchronousServerSocketChannel and optionally bind the returned socket channel to an address:

AsynchronousServerSocketChannel server 
  = AsynchronousServerSocketChannel.open().bind(null);

We have passed in null so that the system can auto-assign an address. Then, we call the accept method on the returned server SocketChannel:

Future<AsynchronousSocketChannel> future = server.accept();

When we call the accept method of a ServerSocketChannel in the old IO, it blocks until an incoming connection is received from a client. But the accept method of an AsynchronousServerSocketChannel returns a Future object right away.

The generic type of the Future object is the return type of the operation. In our case above, it is AsynchronousSocketChannel but it could just as well have been Integer or String, depending on the ultimate return type of the operation.

We can use the Future object to query the state of the operation:

future.isDone();

This API returns true if the underlying operation already completed. Note that completion, in this case, may mean normal termination, an exception, or cancellation.

We can also explicitly check if the operation has been canceled:

future.isCancelled();

It only returns true if the operation was canceled before completing normally, otherwise, it returns false. Cancellation is performed by the cancel method:

future.cancel(true);

The call cancels the operation represented by the Future object. The parameter indicates that even if the operation has started, it can be interrupted. Once an operation has completed, it cannot be canceled

To retrieve the result of a computation, we use the get method:

AsynchronousSocketChannel client= future.get();

If we call this API before the operation completes, it will block until completion and then return the result of the operation.

4. The CompletionHandler Approach

The alternative to using Future to handle operations is a callback mechanism using the CompletionHandler class. The asynchronous channels allow a completion handler to be specified to consume the result of an operation:

AsynchronousServerSocketChannel listener
  = AsynchronousServerSocketChannel.open().bind(null);

listener.accept(
  attachment, new CompletionHandler<AsynchronousSocketChannel, Object>() {
    public void completed(
      AsynchronousSocketChannel client, Object attachment) {
          // do whatever with client
      }
    public void failed(Throwable exc, Object attachment) {
          // handle failure
      }
  });

The completed callback API is invoked when the I/O operation completes successfully. The failed callback is invoked if the operation has failed.

These callback methods accept other parameters – to allow us to pass in any data we think may be suitable to tag along with the operation. This first parameter is available as the second parameter of the callback method.

Finally, a clear scenario is – using the same CompletionHandler for different asynchronous operations. In this case, we’d benefit from tagging each operation to provide context when handling the results we will see this in action in the following section.

5. Conclusion

In this article, we have explored introductory aspects of the Asynchronous Channel APIs of Java NIO2.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)