AbstractSelectableChannel#register(Selector sel, int ops, Object att)
public final SelectionKey register(Selector sel, int ops,
Object att)
throws ClosedChannelException
{
synchronized (regLock) {
//如果通道没有开启则抛出异常
if (!isOpen())
throw new ClosedChannelException();
//如果注册的监听事件不是读、写、连接事件则抛出异常
if ((ops & ~validOps()) != 0)
throw new IllegalArgumentException();
//如果是阻塞channel则抛出异常
if (blocking)
throw new IllegalBlockingModeException();
//查找通道的SelectionKey
SelectionKey k = findKey(sel);
if (k != null) {
//如果SelectionKey 不为空则注册关心的事件类型
k.interestOps(ops);
k.attach(att);
}
if (k == null) {
// New registration
synchronized (keyLock) {
if (!isOpen())
throw new ClosedChannelException();
//如果SelectionKey 为空则将通道注册到Selector
k = ((AbstractSelector)sel).register(this, ops, att);
addKey(k);
}
}
return k;
}
}
SelectorImpl#register(AbstractSelectableChannel var1, int var2, Object var3):SelectionKey
protected final SelectionKey register(AbstractSelectableChannel var1, int var2, Object var3) {
if (!(var1 instanceof SelChImpl)) {
throw new IllegalSelectorException();
} else {
//根据channel和selector创建一个SelectionKeyImpl 对象
SelectionKeyImpl var4 = new SelectionKeyImpl((SelChImpl)var1, this);
//向SelectionKeyImpl中设置附件内容
var4.attach(var3);
Set var5 = this.publicKeys;
synchronized(this.publicKeys) {
//将SelectionKeyImpl 注册到selector中去
this.implRegister(var4);
}
//设置感兴趣事件类型
var4.interestOps(var2);
return var4;
}
}
WindowsSelectorImpl#implRegister(SelectionKeyImpl var1) 将selectionKey注册到操作系统的Selector系统调用上
protected void implRegister(SelectionKeyImpl var1) {
Object var2 = this.closeLock;
synchronized(this.closeLock) {
if (this.pollWrapper == null) {
throw new ClosedSelectorException();
} else {
//如果存储selectionKey的数组容量不够则扩容
this.growIfNeeded();
//将selectionKey存入数值
this.channelArray[this.totalChannels] = var1;
var1.setIndex(this.totalChannels);
this.fdMap.put(var1);
//将key添加到数组
this.keys.add(var1);
//将通道的文件描述符存储到pollWrapper中
this.pollWrapper.addEntry(this.totalChannels, var1);
++this.totalChannels;
}
}
}
channel注册涉及的UML图: