5

Netty3 4线程模型的区别

 3 years ago
source link: http://novoland.github.io/%E7%BD%91%E7%BB%9C/2014/07/26/Netty3%204%E7%BA%BF%E7%A8%8B%E6%A8%A1%E5%9E%8B%E7%9A%84%E5%8C%BA%E5%88%AB.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Netty3 4线程模型的区别

Netty3中,Pipeline中事件的处理可能是嵌套的,这是个串行的过程(对于单个线程而言):
Alt text

Netty3中,Upstream事件一般是由底层transport service发起的,发起者必然是IO线程;但Downstream事件可以由任意线程发起并处理,这就给Handler/Sink带来了并发问题,如并发地在一个Channel上调用write,或并发地调用Channel.close()。
Alt text

并发写会导致数据交错,NioWorker的做法是将write事件 缓存在队列中由IO线程串行执行,但其他事件如close/bind 直接由发起线程执行;不同的是,OioWorker 直接在发起线程中处理write事件,但它通过对 socket 输出流加锁保证线程安全

另一个问题是,downstream事件的处理结果通常要用一个upstream事件来传递,比如发起一个exceptionCaught事件,但发起者可以是 User thread,此时必须要把事件传递给IO thread才满足“upstream事件由IO线程发起“的约束。

Netty4提供了一个更简单的线程模型,事件的处理(无论对于handler还是sink)都必须在IO线程中进行,write事件的入队提前到了第一个handler中:在第一个handler中判断发起线程是否IO线程,是则处理,否则将事件连带handler一起放入eventloop排队,这也意味着handler始终在一个单线程环境中运行。优点是并行转串行,handler不用担心并发问题,缺点是带来了延迟。

不管是3还是4,无论如何不要阻塞io线程,否则后续连接上的事件无法处理。

Powered by Jekyll  |  Theme 3-Jekyll


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK