Netty源码细节之IO线程(EventLoop)

16 篇文章 0 订阅
12 篇文章 0 订阅
[b]先从一个简单的代码示例开始 [/b]

服务端启动代码示例


// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new EchoServerHandler());
}
});
// Start the server.
ChannelFuture f = b.bind(PORT).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}


在看这个示例之前, 先抛出[color=red][b]Netty中几个重要组件[/b][/color]以及他们之间的简单关系, 方便理解后续的代码展开.

1.EventLoopGroup
[b]2.EventLoop [/b]
3.boss/worker
4.channel
5.event(inbound/outbound)
[b]6.pipeline [/b]
7.handler

----------------------------------------------------------------------------------
[b]1.EventLoopGroup中包含一组EventLoop [/b]

2.EventLoop的大致数据结构是
a.一个任务队列
b.一个延迟任务队列(schedule)
c.EventLoop绑定了一个Thread, 这直接避免了pipeline中的线程竞争(在这里更正一下4.1.x以及5.x由于引入了FJP[4.1.x现在又去掉了FJP], 线程模型已经有所变化, EventLoop.run()可能被不同的线程执行,[color=blue][b]但大多数scheduler(包括FJP)在EventLoop这种方式的使用下都能保证在handler中不会"可见性(visibility)"问题,[/b][/color] 所以为了理解简单, 我们仍可以理解为为EventLoop绑定了一个Thread)
d.每个EventLoop有一个Selector, [color=red][b]boss用Selector处理accept, worker用Selector处理read,write等 [/b][/color]

3.boss可简单理解为Reactor模式中的mainReactor的角色, worker可简单理解为subReactor的角色
a.boss和worker共用EventLoop的代码逻辑
[color=red][b]b.在不bind多端口的情况下bossEventLoopGroup中只需要包含一个EventLoop [/b][/color]
c.workerEventLoopGroup中一般包含多个EventLoop
d.Netty server启动后会把一个监听套接字ServerSocketChannel注册到bossEventLoop中
e.通过上一点我们知道[color=red][b]bossEventLoop一个主要责任就是负责accept连接(channel)然后dispatch到worker [/b][/color]
[b]f.worker接到boss爷赏的channel后负责处理此chanel后续的read,write等event
[/b]
4.channel分两大类ServerChannel和channel, ServerChannel对应着监听套接字(ServerSocketChannel), channel对应着一个网络连接

5.有两大类event:inbound/outbound(上行/下行)

6.event按照一定顺序在pipeline里面流转, 流转顺序参见下图

[b]7.pipeline里面有多个handler, 每个handler节点过滤在pipeline中流转的event[/b], 如果判定需要自己处理这个event,则处理(用户可以在pipeline中添加自己的handler)

[img]http://dl2.iteye.com/upload/attachment/0121/1768/b6b70313-18dc-3992-9b23-1ee35be84749.png[/img]

IO线程组的创建:[color=red][b]NioEventLoopGroup[/b][/color]


public NioEventLoopGroup(int nEventLoops, Executor executor, final SelectorProvider selectorProvider) {
super(nEventLoops, executor, selectorProvider);
}


[b]nEventLoops:[/b]
Group内EventLoop个数, 每个EventLoop都绑定一个线程, 默认值为cpu cores * 2, 对worker来说, 这是一个经验值, 当然如果worker完全是在处理cpu密集型任务也可以设置成 cores + 1 或者是根据自己场景测试出来的最优值.
一般boss group这个参数设置为1就可以了, 除非需要bind多个端口.
boss和worker的关系可以参考Reactor模式,网上有很多资料.简单的理解就是:[color=red][b]boss负责accept连接然后将连接转交给worker, worker负责处理read,write等 [/b][/color]

[b]executor: [/b]
Netty 4.1.x版本以及5.x版本采用Doug Lea在jsr166中的ForkJoinPool作为默认的executor, 每个EventLoop在一次run方法调用的生命周期内都是绑定在fjp中一个Thread身上(EventLoop父类SingleThreadEventExecutor中的thread实例变量)
目前Netty由于线程模型的关系并没有利用fjp的work−stealing, 关于fjp可参考这个paper [url]http://gee.cs.oswego.edu/dl/papers/fj.pdf [/url]

[b]selectorProvider: [/b]
group内每一个EventLoop都要持有一个selector, 就由它提供了上面反复提到过每个EventLoop都绑定了一个Thread(可以这么理解,但5.x中实际不是这样子), 这是netty4.x以及5.x版本相对于3.x版本最大变化之一, 这个改变从根本上避免了outBound/downStream事件在pipeline中的线程竞争

父类构造方法:


private MultithreadEventExecutorGroup(int nEventExecutors,
Executor executor,
boolean shutdownExecutor,
Object... args) {
// ......

if (executor == null) {
executor = newDefaultExecutorService(nEventExecutors); // 默认fjp
shutdownExecutor = true;
}

children = new EventExecutor[nEventExecutors];
if (isPowerOfTwo(children.length)) {
chooser = new PowerOfTwoEventExecutorChooser();
} else {
chooser = new GenericEventExecutorChooser();
}

for (int i = 0; i < nEventExecutors; i++) {
boolean success = false;
try {
children[i] = newChild(executor, args); // child即EventLoop
success = true;
} catch (Exception e) {
// ......
} finally {
if (!success) {
// 失败处理......
}
}
}
// ......
}


1.如果之前没有指定executor默认为fjp, fjp的parallelism值即为nEventExecutors
executor(scheduler)可以由用户指定, 这给了第三方很大的自由度, 总会有高级用户想完全的控制scheduler, 比如Twitter的Finagle. [url]https://github.com/netty/netty/issues/2250[/url]

2.接下来创建children数组, 即EventLoop[],现在可以知道 EventLoop与EventLoopGroup的关系了.

[b]3.后面会讲到boss把一个就绪的连接转交给worker时会从children中取模拿出一个EventLoop然后将连接交给它. [/b]
值得注意的是由于这段代码是热点代码, 作为"优化狂魔"netty团队岂会放过这种优化细节? 如果children个数为2的n次方, 会采用和HashMap同样的优化方式[位操作]来代替取模操作:
children[childIndex.getAndIncrement() & children.length - 1]

4.接下来的newChild()是构造EventLoop, 下面会详细展开
接下来我们分析NioEventLoop

PS:Netty 4.0.16版本开始由Norman Maurer提供了EpollEventLoop, 基于Linux Epoll ET实现的JNI(java nio基于Epoll LT)Edge Triggered(ET) VS Level Triggered(LT)http://linux.die.net/man/7/epoll.这在一定程度上提供了更高效的传输层, 同时也减少了java层的gc, 这里不详细展开了, 感兴趣的可看这里 Native transport for Linux wikihttp://netty.io/wiki/native-transports.html

[color=red][b]NioEventLoop [/b][/color]


//接上面的newchild()
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
return new NioEventLoop(this, executor, (SelectorProvider) args[0]);
}

构造方法:
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider) {
super(parent, executor, false);
// ......
provider = selectorProvider;
selector = openSelector();
}

父类构造方法:
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp) {
super(parent);
// ......
this.addTaskWakesUp = addTaskWakesUp;
this.executor = executor;
taskQueue = newTaskQueue();
}


1.我们看到首先是打开一个selector, selector的优化细节我们下面会讲到

2.接着在父类中会构造一个task queue, 这是一个lock-free的MPSC队列,[b] netty的线程(比如worker)一直在一个死循环状态中(引入fjp后是不断自己调度自己)去执行IO事件和非IO事件.
除了IO事件, 非IO事件都是先丢到这个MPSC队列再由worker线程去异步执行. [/b]
MPSC即multi-producer single-consumer([color=red][b]多生产者, 单消费者[/b][/color]) 完美贴合netty的IO线程模型(消费者就是EventLoop自己咯), 情不自禁再给"优化狂魔"点32个赞.

跑题一下:
对lock-free队列感兴趣可以仔细看看MpscLinkedQueue的代码, 其中一些比如为了避免伪共享的long padding优化也是比较有意思的.
如果还对类似并发队列感兴趣的话请转战这里 https://github.com/JCTools/JCTools
另外报个八卦料曾经也有人提出在这里引入disruptor后来不了了之, 相信用disruptor也会很有趣
https://github.com/netty/netty/issues/447 


接下来展开openSelector()详细分析


private Selector openSelector() {
final Selector selector;
try {
selector = provider.openSelector();
} catch (IOException ignored) {}

if (DISABLE_KEYSET_OPTIMIZATION) {
return selector;
}

try {
SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();

Class<?> selectorImplClass =
Class.forName("sun.nio.ch.SelectorImpl", false, PlatformDependent.getSystemClassLoader());

// Ensure the current selector implementation is what we can instrument.
if (!selectorImplClass.isAssignableFrom(selector.getClass())) {
return selector;
}

Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");

selectedKeysField.setAccessible(true);
publicSelectedKeysField.setAccessible(true);

selectedKeysField.set(selector, selectedKeySet);
publicSelectedKeysField.set(selector, selectedKeySet);

selectedKeys = selectedKeySet;
logger.trace("Instrumented an optimized java.util.Set into: {}", selector);
} catch (Throwable t) {
selectedKeys = null;
logger.trace("Failed to instrument an optimized java.util.Set into: {}", selector, t);
}

return selector;
}


1.首先openSelector, 这是jdk的api就不详细展开了
2.接着DISABLE_KEYSET_OPTIMIZATION是判断是否需要对sun.nio.ch.SelectorImpl中的selectedKeys进行优化, 不做配置的话默认需要优化.
3.哪些优化呢?原来SelectorImpl中的selectedKeys和publicSelectedKeys是个HashSet, 新的数据结构是双数组A和B, [color=red][b]初始大小1024, 避免了HashSet的频繁自动扩容, [/b][/color]
processSelectedKeys时先使用数组A,再一次processSelectedKeys时调用flip的切换到数组B, 如此反复
另外我大胆胡说一下我个人对这个优化的理解, 如果对于这个优化只是看到避免了HashSet的自动扩容, 我还是认为这有点小看了"优化狂魔"们, 我们知道HashSet用拉链法解决哈希冲突, 也就是说它的数据结构是数组+链表,
而我们又知道, 对于selectedKeys, 最重要的操作是遍历全部元素, 但是数组+链表的数据结构对于cpu的 cache line 来说肯定是不够友好的.如果是直接遍历数组的话, cpu会把数组中相邻的元素一次加载到同一个cache line里面(一个cache line的大小一般是64个字节), 所以遍历数组无疑效率更高.
有另一队优化狂魔是上面论调的支持者及推广者 disruptor [url]https://github.com/LMAX-Exchange/disruptor [/url]


EventLoop构造方法的部分到此介绍完了, 接下来看看EventLoop怎么启动的, 启动后都做什么


//EventLoop的父类SingleThreadEventExecutor中有一个startExecution()方法, 它最终会调//用如下代码:

private final Runnable asRunnable = new Runnable() {
@Override
public void run() {
updateThread(Thread.currentThread());

if (firstRun) {
firstRun = false;
updateLastExecutionTime();
}

try {
SingleThreadEventExecutor.this.run();
} catch (Throwable t) {
cleanupAndTerminate(false);
}
}
};

//这个Runnable不详细解释了, 它用来实现IO线程在fjp中死循环的自己调度自己, 只需要看 //SingleThreadEventExecutor.this.run() 便知道, 接下来要转战EventLoop.run()方法了

protected void run() {
boolean oldWakenUp = wakenUp.getAndSet(false);
try {
if (hasTasks()) {
selectNow();
} else {
select(oldWakenUp);
if (wakenUp.get()) {
selector.wakeup();
}
}

cancelledKeys = 0;
needsToSelectAgain = false;
final int ioRatio = this.ioRatio;
if (ioRatio == 100) {
processSelectedKeys();
runAllTasks();
} else {
final long ioStartTime = System.nanoTime();
processSelectedKeys();
final long ioTime = System.nanoTime() - ioStartTime;
runAllTasks(ioTime * (100 - ioRatio) / ioRatio);
}

if (isShuttingDown()) {
closeAll();
if (confirmShutdown()) {
cleanupAndTerminate(true);
return;
}
}
} catch (Throwable t) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {}
}
scheduleExecution();
}


为了避免代码占用篇幅过大, 我去掉了注释部分
首先强调一下EventLoop执行的任务分为两大类:[color=red][b]IO任务和非IO任务. [/b][/color]
1)IO任务比如: [color=red][b]OP_ACCEPT、OP_CONNECT、OP_READ、OP_WRITE[/b][/color]
2)非IO任务比如: [b][color=red]bind、channelActive等 [/color][/b]

接下来看这个run方法的大致流程:
1.先调用hasTask()判断是否有非IO任务, 如果有的话, 选择调用非阻塞的selectNow()让select立即返回, 否则以阻塞的方式调用select. 后续再分析select方法, 目前先把run的流程梳理完.

2.两类任务执行的时间比例由ioRatio来控制, 你可以通过它来限制非IO任务的执行时间, 默认值是50, 表示允许非IO任务获得和IO任务相同的执行时间, 这个值根据自己的具体场景来设置.

3.接着调用processSelectedKeys()处理IO事件, 后边会再详细分析.

[b]4.执行完IO任务后就轮到非IO任务了runAllTasks(). [/b]

5.最后scheduleExecution()是自己调度自己进入下一个轮回, 如此反复, 生命不息调度不止, 除非被shutDown了, isShuttingDown()方法就是去检查state是否被标记为ST_SHUTTING_DOWN.

转自:[url]http://budairenqin.iteye.com/blog/2215896[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值