---
title: "netty源码分析之ChannelFuture"
author: "asialee"
date: "2013-01-26T19:42:28Z"
tags: ["netty"]
categories: ["编程语言"]
slug: "netty-channelfuture"
draft: false
lastmod: "2013-01-27T12:46:34Z"
id: 1776155
url: "https://asialee.iteye.com/blog/1776155"
---

在netty里面所有的nio相关的操作都是异步的，返回一个channelfuture对象，这个里面可以添加一些listener，然后再相关操作完成后进行触发，最主要的是通过这个对象可以查询相关操作的执行情况，是成功了，还是失败了。

         我们来就来看看DefaultChannelFuture的实现就好，我们应该能猜到netty的思想，里面有一个listener的集合，addListener会添加listener到集合里面，然后再真正的io操作完成之后来触发相应的listener，这里面有很多关于多线程的程序，这个还不是很了解，应该后面多恶补恶补。

          

```
private void notifyListeners() {
        // This method doesn't need synchronization because:
        // 1) This method is always called after synchronized (this) block.
        //    Hence any listener list modification happens-before this method.
        // 2) This method is called only when 'done' is true.  Once 'done'
        //    becomes true, the listener list is never modified - see add/removeListener()
        if (firstListener != null) {
            notifyListener(firstListener);
            firstListener = null;

            if (otherListeners != null) {
                for (ChannelFutureListener l: otherListeners) {
                    notifyListener(l);
                }
                otherListeners = null;
            }
        }
    }
```