Java NIO Framework Netty Tutorial (16)-serverbootstrap launch process source code analysis

Source: Internet
Author: User

There is no update of the article, a variety of reasons have it. Moving the trivial, after moving the ease hehe. However, Onecoder understand, must not relax. For Netty's study, it's time to go a little deeper.

Therefore, this time Onecoder spent a few days, carefully combed the source of Netty , summed up the serverbootstrap start and task processing process, basically covers the key structure of Netty. Onecoder summed up a flowchart:

The figure is onecoder by reading the Netty source code, gradually recorded. A basic description of the start-up process for Netty services. Here is a detailed explanation.

First of all, our smooth flow is based on Niosocketserver . That is, based on the Java NIO Selector implementation approach. In the sixth lecture on the Java NIO Framework Netty Tutorial (vi)-java NIO selector mode, we already know several key points of using Selector, so here we also focus on how these points are used in Netty.

Many people who have seen Netty source say that Netty source code is very beautiful. But where is the beauty? Netty uses a channelfactory to determine the type of protocol you are currently using (NIO/OIO, etc.), for example, Onecoder is using nioserversocket, Then the Factory that needs to be declared is nioserversocketchannelfactory, which declares the Factory, determines the channel you use, Pipeline and pipeline, the type of sink that specifically deals with the business. This kind of use is very concise, the learning curve is very low, switch implementation is very easy.

Netty uses the event-based pipeline architecture design, where events flow through the pipeline (Pipeline) and are referred to (via Pipelinesink) to the appropriate processor (Handler). The matching of these key element types is determined by the ChannelFactory of the start declaration.

NettyThe business within the framework also follows this process,ServerEnd-bound port.Binderis actually aHandler, after constructingBinder, you will declare aPipelinePipeline, and assigns a newChannel。NettyInNewchannelIn Java, the corresponding call to theServersocketchannel.openmethod to open aChannel。 And then TriggerFirechannelopenEvent. The acceptance of this event can be replicated.Binderitself received this event. In the handling of the event, continue to complete the binding of the specific port. CorrespondingSelectorIn thesocketchannel.socket (). bind ()。 And then TriggerFirechannelboundEvent. By default, this event is not accepted and continues to start constructionBossThe thread pool. We know that inNettyInBossThread pooling is the core thread pool used to accept and distribute requests. So inChannelAfter binding, it is necessary to startBossLine Castle, ready to acceptClientThe request that was sent. InBossConstructor, the first time you register aselectorTypes of events of interest,selectionkey.op_accept。 At this point, the use described in the sixth lectureSelectorA few key steps are reflected inNettyIn the. InBossA dead loop is started in the query to see if there is an event of interest that occurs, for the first time the client registers the event,BossWill beChannelRegister toworkerSave.

To add, this is also the omitted part of the graph, which is about the timing of the worker thread pool initialization. The construction of the worker Pool is ready at the very beginning of the construction of the ChannelFactory . In Nioserversocketchannelfactory 's constructor, a nioworkerpoolis new. In the constructor of the base class Abstractnioworkerpool of Nioworkerpool , the openselector method is called, which also opens a Selector, and the worker thread pool is started. <

PrivatevoidOpenselector(){Try{Selector=Selector.Open();}Catch(ThrowableT){ThrowNewChannelexception(&quot;FailedToCreateASelector.&quot;,T);}Start the worker thread with the new Selector.BooleanSuccess=False;Try{Deadlockproofworker.Start(Executor,NewThreadrenamingrunnable(This,&quot;NewI/OWorker#&quot;+Id));Success=True;}Finally{If(!Success){Release The Selector if the execution fails.Try{Selector.Close();}Catch(ThrowableT){Logger.Warn(&quot; Failed to close a selector.&< span class= "n" >quott; } selector = null//the method would return to the caller at this point. } } assert selector != null &amp;&amp selector. ();               /span>                

At this point, the run logic in Abstractnioworker is started in a thread. The same is the Loop Processing Task queue.

processRegisterTaskQueue();processEventQueue();processWriteTaskQueue();processSelectedKeys(selector.selectedKeys());

In this way, the design makes the receiving and processing modules of the event fully decoupled.

This shows that if you want to switch from NIO to OIO, you only need to construct a different channelfacotry. It was simple and elegant.

Java NIO Framework Netty Tutorial (16)-serverbootstrap launch process source code analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.