在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;
- }
- }
- }