Netty的服務端怎麼和java NIO聯繫起來的,一直很好奇這塊內容,這裏跟下代碼,下篇文章看下Channel相關的知識。html
finalChannelFuture initAndRegister(){
finalChannel channel = channelFactory().newChannel();//
try{
init(channel);
}catch(Throwable t){
channel.unsafe().closeForcibly();//當即關閉通道且不會觸發事件
//由於這個通道尚未註冊到EventLoop,因此咱們須要強制GlobalEventExecutor的使用。
returnnewDefaultChannelPromise(channel,GlobalEventExecutor.INSTANCE).setFailure(t);
}
//註冊一個EventLoop
ChannelFuture regFuture = group().register(channel);
//註冊失敗
if(regFuture.cause()!=null){
if(channel.isRegistered()){
channel.close();
}else{
channel.unsafe().closeForcibly();
}
}
// If we are here and the promise is not failed, it's one of the following cases:
// 程序運行到這裏且promise沒有失敗,可能有以下幾種狀況
// 1) If we attempted registration from the event loop, the registration has been completed at this point.
// 若是試圖註冊到一個EventLoop,該註冊完成,
// i.e. It's safe to attempt bind() or connect() now because the channel has been registered.
// 2) If we attempted registration from the other thread, the registration request has been successfully
// added to the event loop's task queue for later execution.
// 若是試圖註冊到其餘線程,該註冊已經成功,可是沒有完成,添加一個事件到任務隊列中,等會執行
// i.e. It's safe to attempt bind() or connect() now:
// because bind() or connect() will be executed *after* the scheduled registration task is executed
// because register(), bind(), and connect() are all bound to the same thread.
return regFuture;
}
@Override
publicChannelFutureregister(Channel channel){
return next().register(channel);
}
@Override
publicChannelFutureregister(finalChannel channel,finalChannelPromise promise){
if(channel ==null){
thrownewNullPointerException("channel");
}
if(promise ==null){
thrownewNullPointerException("promise");
}
channel.unsafe().register(this, promise);
return promise;
}
@Override
publicfinalvoidregister(EventLoop eventLoop,finalChannelPromise promise){
if(eventLoop ==null){
thrownewNullPointerException("eventLoop");
}
if(isRegistered()){
promise.setFailure(newIllegalStateException("registered to an event loop already"));
return;
}
if(!isCompatible(eventLoop)){
promise.setFailure(
newIllegalStateException("incompatible event loop type: "+ eventLoop.getClass().getName()));
return;
}
AbstractChannel.this.eventLoop = eventLoop;
if(eventLoop.inEventLoop()){
register0(promise);
}else{
try{
eventLoop.execute(newOneTimeTask(){
@Override
publicvoid run(){
register0(promise);
}
});
}catch(Throwable t){
logger.warn(
"Force-closing a channel whose registration task was not accepted by an event loop: {}",
AbstractChannel.this, t);
closeForcibly();
closeFuture.setClosed();
safeSetFailure(promise, t);
}
}
}
@Override
protectedvoid doRegister()throwsException{
boolean selected =false;
for(;;){
try{
selectionKey = javaChannel().register(eventLoop().selector,0,this);
return;
}catch(CancelledKeyException e){
if(!selected){
// Force the Selector to select now as the "canceled" SelectionKey may still be
// cached and not removed because no Select.select(..) operation was called yet.
eventLoop().selectNow();
selected =true;
}else{
// We forced a select operation on the selector before but the SelectionKey is still cached
// for whatever reason. JDK bug ?
throw e;
}
}
}
}
wakeup
方法所得的結果
privatestaticvoid doBind0(
finalChannelFuture regFuture,finalChannel channel,
finalSocketAddress localAddress,finalChannelPromise promise){
// This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up
// the pipeline in its channelRegistered() implementation.
channel.eventLoop().execute(newRunnable(){
@Override
publicvoid run(){
if(regFuture.isSuccess()){
channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}else{
promise.setFailure(regFuture.cause());
}
}
});
}
@Override
protectedvoid run(){
for(;;){
boolean oldWakenUp = wakenUp.getAndSet(false);
try{
if(hasTasks()){
selectNow();
}else{
select(oldWakenUp);
// 'wakenUp.compareAndSet(false, true)' is always evaluated
// before calling 'selector.wakeup()' to reduce the wake-up
// overhead. (Selector.wakeup() is an expensive operation.)
//
// However, there is a race condition in this approach.
// The race condition is triggered when 'wakenUp' is set to
// true too early.
//
// 'wakenUp' is set to true too early if:
// 1) Selector is waken up between 'wakenUp.set(false)' and
// 'selector.select(...)'. (BAD)
// 2) Selector is waken up between 'selector.select(...)' and
// 'if (wakenUp.get()) { ... }'. (OK)
//
// In the first case, 'wakenUp' is set to true and the
// following 'selector.select(...)' will wake up immediately.
// Until 'wakenUp' is set to false again in the next round,
// 'wakenUp.compareAndSet(false, true)' will fail, and therefore
// any attempt to wake up the Selector will fail, too, causing
// the following 'selector.select(...)' call to block
// unnecessarily.
//
// To fix this problem, we wake up the selector again if wakenUp
// is true immediately after selector.select(...).
// It is inefficient in that it wakes up the selector for both
// the first case (BAD - wake-up required) and the second case
// (OK - no wake-up required).
if(wakenUp.get()){
selector.wakeup();
}
}
cancelledKeys =0;
needsToSelectAgain =false;
finalint ioRatio =this.ioRatio;
if(ioRatio ==100){
processSelectedKeys();
runAllTasks();
}else{
finallong ioStartTime =System.nanoTime();
processSelectedKeys();
finallong ioTime =System.nanoTime()- ioStartTime;
runAllTasks(ioTime *(100- ioRatio)/ ioRatio);
}
if(isShuttingDown()){
closeAll();
if(confirmShutdown()){
break;
}
}
}catch(Throwable t){
logger.warn("Unexpected exception in the selector loop.", t);
// Prevent possible consecutive immediate failures that lead to
// excessive CPU consumption.
try{
Thread.sleep(1000);
}catch(InterruptedException e){
// Ignore.
}
}
}
}