concept ChannelFuture in category netty

appears as: ChnelFuture
Netty in Action

This is an excerpt from Manning's book Netty in Action.

The JDK ships with interface java.util.concurrent.Future, but the provided implementations allow you only to check manually whether the operation has completed or to block until it does. This is quite cumbersome, so Netty provides its own implementation, ChannelFuture, for use when an asynchronous operation is executed.

ChannelFuture provides additional methods that allow us to register one or more ChannelFutureListener instances. The listener’s callback method, operationComplete(), is called when the operation has completed. The listener can then determine whether the operation completed successfully or with an error. If the latter, we can retrieve the Throwable that was produced. In short, the notification mechanism provided by the ChannelFutureListener eliminates the need for manually checking operation completion.

Each of Netty’s outbound I/O operations returns a ChannelFuture; that is, none of them block. As we said earlier, Netty is asynchronous and event-driven from the ground up.

Listing 1.3 shows that a ChannelFuture is returned as part of an I/O operation. Here, connect() will return directly without blocking and the call will complete in the background. When this will happen may depend on several factors, but this concern is abstracted away from the code. Because the thread is not blocked waiting for the operation to complete, it can do other work in the meantime, thus using resources more efficiently.

Listing 1.3. Asynchronous connect

Listing 1.4 shows how to utilize the ChannelFutureListener. First you connect to a remote peer. Then you register a new ChannelFutureListener with the ChannelFuture returned by the connect() call. When the listener is notified that the connection is established, you check the status . If the operation is successful, you write data to the Channel. Otherwise you retrieve the Throwable from the ChannelFuture.

The following sections will add detail to our discussion of the Channel, EventLoop, and ChannelFuture classes which, taken together, can be thought of as representing Netty’s networking abstraction:

  • Almost all methods of ChannelOutboundHandler are passed an instance of ChannelPromise. As a subclass of ChannelFuture, ChannelPromise can also be assigned listeners for asynchronous notification. But ChannelPromise also has writable methods that provide for immediate notification:
    ChannelPromise setSuccess();
    ChannelPromise setFailure(Throwable cause);