類定義:
abstract class AbstractChannelHandlerContext extends DefaultAttributeMap
implements ChannelHandlerContext, ResourceLeakHint {}
類屬性:
next && prev
每個AbstractChannelHandlerContext都儲存有兩個屬性, next和prev, 明顯是做連結清單.
volatile AbstractChannelHandlerContext next;
volatile AbstractChannelHandlerContext prev;
在DefaultChannelPipeline中, 則儲存了名為head和tail的兩個引用:
final AbstractChannelHandlerContext head;
final AbstractChannelHandlerContext tail;
這樣在DefaultChannelPipeline中就實作了一個從head一路next/next到tail, 再從tail一路prev/prev到head的一個雙向連結清單.
inbound && outbound
這兩個屬性用來表明目前handler是inbound還是outbound, 通常和ChannelInboundHandler/ChannelOutboundHandler聯系起來,.
比如HeadContext實作了ChannelOutboundHandler, 而TailContext實作了ChannelInboundHandler, 他們在調用super構造函數時就寫死了inbound和outbound屬性:
final class HeadContext extends AbstractChannelHandlerContext
implements ChannelOutboundHandler, ChannelInboundHandler {
private final Unsafe unsafe;
HeadContext(DefaultChannelPipeline pipeline) {
super(pipeline, null, HEAD_NAME, false, true);
unsafe = pipeline.channel().unsafe();
setAddComplete();
}
}
final class TailContext extends AbstractChannelHandlerContext implements ChannelInboundHandler {
TailContext(DefaultChannelPipeline pipeline) {
super(pipeline, null, TAIL_NAME, true, false);
setAddComplete();
}
}
netty設計上是使用兩個boolean來記錄inbound/outbound,
在DefaultChannelHandlerContext的實作中, 通過檢查傳入的handler來判斷inbound/outbound, 判斷的方法非常直接, instanceof ChannelInboundHandler/ChannelOutboundHandler:
DefaultChannelHandlerContext(
DefaultChannelPipeline pipeline, EventExecutor executor, String name, ChannelHandler handler) {
super(pipeline, executor, name, isInbound(handler), isOutbound(handler));
if (handler == null) {
throw new NullPointerException("handler");
}
this.handler = handler;
}
@Override
public ChannelHandler handler() {
return handler;
}
private static boolean isInbound(ChannelHandler handler) {
return handler instanceof ChannelInboundHandler;
}
private static boolean isOutbound(ChannelHandler handler) {
return handler instanceof ChannelOutboundHandler;
}
類方法:
setRemoved()
這是一個非常特别的屬性, 隻用于非常極端的情況, getter/setter方法如下:
final void setRemoved() {
handlerState = REMOVE_COMPLETE;
}
@Override
public boolean isRemoved() {
return handlerState == REMOVE_COMPLETE;
}
其中setRemoved()還不是public的, 調用的地方隻有一處, 在類DefaultChannelPipeline:
private void callHandlerRemoved0(final AbstractChannelHandlerContext ctx) {
// Notify the complete removal.
try {
try {
// 從context 删除之後不在調用, handlerRemoved()自帶方法
ctx.handler().handlerRemoved(ctx);
} finally {
ctx.setRemoved();
}
} catch (Throwable t) {
fireExceptionCaught(new ChannelPipelineException(
ctx.handler().getClass().getName() + ".handlerRemoved() has thrown an exception.", t));
}
}
AttributeKey 相關方法
ChannelHandlerContext申明繼承AttributeMap, AbstractChannelHandlerContext中有實作AttributeMap要求的兩個方法:
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
return channel().attr(key);
}
@Override
public <T> boolean hasAttr(AttributeKey<T> key) {
return channel().hasAttr(key);
}
最終還是delegate給channel的對應方法了.
Inbound 的IO 事件方法
這些方法最終都是delegate給invoker的對應方法, 以fireChannelRegistered()為例:
@Override
public ChannelHandlerContext fireChannelRegistered() {
// 找到下一個inbound 的 context,并調用invokeChannelRegistered() 方法
invokeChannelRegistered(findContextInbound());
return this;
}
static void invokeChannelRegistered(final AbstractChannelHandlerContext next) {
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeChannelRegistered();
} else {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeChannelRegistered();
}
});
}
}
private void invokeChannelRegistered() {
if (invokeHandler()) {
try {
((ChannelInboundHandler) handler()).channelRegistered(this);
} catch (Throwable t) {
notifyHandlerException(t);
}
} else {
fireChannelRegistered();
}
}
private AbstractChannelHandlerContext findContextInbound() {
// ctx 初始化為指向目前的context, 也就是this
AbstractChannelHandlerContext ctx = this;
do {
// 然後指向ctx 的next 指針,向後找
ctx = ctx.next;
} while (!ctx.inbound); // 檢查是否是inbound,如果不是則繼續next,直到找到下一個
return ctx;
}
這和javadoc中對這些方法的說明一緻: “這些方法會導緻目前Channel的ChannelPipeline中包含的下一個ChannelInboundHandler的相應的方法被調用”
類似的方法有一下:
ChannelHandlerContext fireChannelRegistered();
ChannelHandlerContext fireChannelUnregistered();
ChannelHandlerContext fireChannelActive();
ChannelHandlerContext fireChannelInactive();
ChannelHandlerContext fireExceptionCaught(Throwable cause); // 這個例外!
ChannelHandlerContext fireUserEventTriggered(Object event);
ChannelHandlerContext fireChannelRead(Object msg);
ChannelHandlerContext fireChannelReadComplete();
ChannelHandlerContext fireChannelWritabilityChanged();
但是fireExceptionCaught方法非常的特殊, 與衆不同的是, 這個方法中的next是不區分inbound和outbound的, 直接取this.next:
@Override
public ChannelHandlerContext fireExceptionCaught(final Throwable cause) {
invokeExceptionCaught(next, cause);
return this;
}
static void invokeExceptionCaught(final AbstractChannelHandlerContext next, final Throwable cause) {
ObjectUtil.checkNotNull(cause, "cause");
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeExceptionCaught(cause);
} else {
try {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeExceptionCaught(cause);
}
});
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to submit an exceptionCaught() event.", t);
logger.warn("The exceptionCaught() event that was failed to submit was:", cause);
}
}
}
}
outbound 的 IO方法
ChannelFuture bind(SocketAddress localAddress);
ChannelFuture connect(SocketAddress remoteAddress);
ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress);
ChannelFuture disconnect();
ChannelFuture close();
ChannelFuture deregister();
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return bind(localAddress, newPromise());
}
@Override
public ChannelPromise newPromise() {
return new DefaultChannelPromise(channel(), executor());
}
@Override
public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) {
if (localAddress == null) {
throw new NullPointerException("localAddress");
}
if (isNotValidPromise(promise, false)) {
// cancelled
return promise;
}
// 找到下一個 outbound 的context
final AbstractChannelHandlerContext next = findContextOutbound();
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeBind(localAddress, promise);
} else {
safeExecute(executor, new Runnable() {
@Override
public void run() {
next.invokeBind(localAddress, promise);
}
}, promise, null);
}
return promise;
}
private AbstractChannelHandlerContext findContextOutbound() {
AbstractChannelHandlerContext ctx = this;
do {
// 向前找
ctx = ctx.prev;
} while (!ctx.outbound);
return ctx;
}