【Netty源码解读和权威指南】第89篇:深入理解Netty内存屏障与JMM——如何保证并发安全
上一篇【第88篇】Netty Proxy Protocol支持——获取真实客户端IP下一篇【第90篇】手写MiniNetty——理解Netty设计精髓的最佳方式一、Netty中的volatile// 大量使用volatile保证可见性publicabstractclassAbstractChannel{privatevolatileEventLoopeventLoop;// EventLoop引用privatevolatilebooleanregistered;// 注册状态}publicclassDefaultPromiseV{privatevolatileObjectresult;// 异步结果}publicclassSingleThreadEventExecutor{privatevolatileintstate;// 关闭状态}// NioEventLoop空轮询检测privateintselectCnt;// volatile二、CAS无锁操作// Channel关闭状态privatebooleancompareAndSetClose(){returnCLOSE_UPDATER.compareAndSet(this,0,1);}// Promise结果设置publicbooleantrySuccess(Vresult){returnRESULT_UPDATER.compareAndSet(this,null,result);}// 引用计数publicbooleanrelease(){returnREFCNT_UPDATER.decrementAndGet(this)0;}三、happens-before保证EventLoop线程内的happens-before 用户线程ctx.executor().execute(task1) ↓ happens-before EventLoop线程执行task1 ↓ happens-before单线程顺序执行 EventLoop线程执行task2 ↓ happens-before EventLoop线程执行task3关键同一个EventLoop线程内的所有操作天然满足happens-before四、避免伪共享// Contended注解避免伪共享sun.misc.ContendedpublicclassSingleThreadEventExecutor{privatevolatileintstate;privatevolatileintthreadState;// 填充保证在不同缓存行}上一篇【第88篇】Netty Proxy Protocol支持——获取真实客户端IP下一篇【第90篇】手写MiniNetty——理解Netty设计精髓的最佳方式