NOTES ON
NETTY PART 3
RICK HIGHTOWER’S
CHANNEL PIPELINES, AND
EVENT LOOPS
About Rick hightower
About Rick
• Implemented Microservices, Vert.x/Netty at massive scale
• Author of QBit, microservices lib and Boon, Json parser and utility lib
• Founder of Mammatus Technology
• Rick’s Twitter, Rick’s LinkedIn, Rick’s Blog, Rick’s Slideshare
Great book on Netty!
https://www.manning.com/books/netty-in-
action
Great talk about Netty Best Practices given at Facebook,
then Twitter University
https://goo.gl/LbXheq
http://www.infoq.com/presentations/apple-netty
Great talk about Netty at scale
Previous slide deck
Previous SLIDE DECK
• Notes on Netty Basics Slideshare
• Part 1:
http://www.slideshare.net/richardhig
htower/notes-on-netty-baics
• Part 2:
http://www.slideshare.net/richardh
ightower/netty-notes-part-2-
transports-and-buffers
• Notes on Netty Basics Google slides
• Part 1: https://goo.gl/aUGm2N
• Part 2: https://goo.gl/xZZhVs
CHANNEL
PIPELINES
Chaining channel handlers
ChannelPipeline
• Channel - Socket
• ByteBuf - container for bytes of message
• ChannelHandler process / transform messages
• ChannelPipeline - forms chain of ChannelHandlers
Lifecycle of a channel
Channel Lifecycle states
• Active
• connected to remote peer
• Inactive
• disconnected from remote peer
• Unregistered
• created
• Registered
• channel associated with event loop
methods on ChannelHandler for lifecycle event
ChannelHandler Lifecycle Events
• handlerAdded()
• added to ChannelPipeline
• handlerRemoved()
• removed from ChannelPipeline
• exceptionCaught()
• error during ChannelPipeline processing
event notification event methods for ChannelInboundHander
ChannelInboundHandler lifecycle methods for Channel
• channelRegistered() - Channel married to an event loop
• channelUnregistered() - Channel divorced from event loop
• channelActive() - connected
• channelInactive() - disconnected
• channelReadComplete() - read operation completed
• channelRead() - data is read on channel
• channelWritabilityChanged() - outgoing IO buffer/limit is met or not
• userEventTriggered() - someone passed a POJO to the event loop
Let it go. Let it go. Can't hold it back anymore
Releasing messages
• Not a good idea to override read
unless you know what you are doing
• you must free up pooled resources
calling
ReferenceCountUtil.release(messag
e)
• Use SimpleChannelInboundHandler
and override channelRead0() instead,
netty will free up message resource for
you
java -Dio.netty.leakDetectionLevel=ADVANCED
You can leak on write or read
Handler for outbound
ChannelOutboundHandler
• Outbound operations
• methods invoked by
• Channel, ChannelPipeline, and ChannelHandlerContext.
• Can defer operation or event
• Powerful level of control
• Many Methods take a ChannelPromise which extends ChannelFuture and
provides ability to mark as succeeded or failed (setSuccess(), setFailure())
• You should mark promise failed or succeeded and also release resources
lifecycle event methods
ChannelOutboundHandler
• bind(channelHandlerContext, localSocketAddress, channelPromise)
• listen to address for connections request event
• connect(channelHandlerContext, socketAddress, channelPromise)
• connect to remote peer request event
• disconnect(channelHandlerContext, channelPromise)
• disconnect from remote peer request event
• close(channelHandlerContext, channelPromise)
• close channel request event
lifecycle event methods
ChannelOutboundHandler
• deregister(channelHandlerContext, channelPromise)
• removed from event loop request event
• read(channelHandlerContext)
• read more data from channel request event
• flush(channelHandlerContext)
• flush data to remote peer request event
• write(channelHandlerContext, message:Object, channelPromise)
• write data to channel request event
chain of channel handlers
ChannelPipeline
• ChannelPipeline is chain of ChannelHandlers
• handlers intercept inbound and outbound events through Channel
• ChannelHandlers process application IO data
• Channel processes IO events
• New Channel assigned to new ChannelPipeline
• relationship is permanent
• no cheating! Channel can’t attach to another ChannelPipeline
• Channel can’t leave ChannelPipeline
• Direction determines if event handled by ChannelInboundHandler or a
ChannelOutboundHandler
• Unhanded events go to next Channel in chain
ChannelHandlers can modify ChannelPipeline
ChannelPipeline can be edited
• ChannelHandler methods to change ChannelPipeline
• addFirst()
• addBefore()
• addAfter()
• addLast()
• remove()
• replace()
Used by Netty to fire events inbound
ChannelPipeline methods
• fireChannelRegistered
• fireChannelUnregistered
• fireChannelActive
• fireChannelInactive
• fireExceptionCaught
• fireUserEventTriggered - user defined event so you can pass a POJO to the channel
• fireChannelRead
• fireChannelReadComplete
Outbound methods
ChannelPipeline methods
• bind - listen to a port, binds channel to port/address
• connect - connect to a remote address
• disconnect - disconnect from a remote address
• close - close the channel after next channel handler is called
• deregister
• flush
• write
• writeAndFlush
• read
Managing passing the events to next handler in chain
ChannelHandlerContext
• Associates ChannelHandler and ChannelPipeline
• Created when ChannelHandler added to a ChannelPipeline
• Manages interaction of its ChannelHandler to others in
ChannelPipeline
• Use context instead of pipeline (most often) as it involves a shorter
event flow
• otherwise must go through whole chain from start
Methods
ChannelHandlerContext
• channel - returns the Channel
• bind, close, connect, disconnect
• read, write
• deregister
• executor - returns EventExecutor (has thread pool scheduling interface)
• fireChannelActive, fireChannelInactive, fireChannelRead, fireChannelReadComplete
• handler - returns corresponding handler
• isRemoved - has the handler been removed?
• name - name of the instance
• pipeline - returns the associated pipeline
In Bound Exception handling
public class MyInboundExceptionHandler
extends ChannelInboundHandlerAdapter {
…
@Override
public void exceptionCaught(ChannelHandlerContext
channelHandlerContext,
Throwable cause) {
logger.error(cause);
channelHandlerContext.close();
}
}
Outbound Exception handling
public class MyHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write( final ChannelHandlerContext channelHandlerContext,
final Object message,
final ChannelPromise channelPromise) {
channelPromise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(final ChannelFuture channelFuture) {
if (!channelFuture.isSuccess()) {
logger.error(channelFuture.cause());
channelFuture.channel().close();
}
}
});
}
}
EVENT LOOPS
Threading model specifics
Event Loop And Threading model
• Threading model specifies is key to understanding Netty
• When threads are spawned is very important to your application code
• You have to understand trade-offs and specifics of Netty
• Multi cores are common occurrence
• Netty uses Executor API interfaces to schedule EventLoop tasks
• Netty tries to reduce cost of thread hand off and CPU cache line moving about by limiting the
#of threads to handle IO
• Less is more by reducing “context switching"
• Increases CPU Register, L1, L2, cache hits by keeping things in same thread
• Reduce wake up cost of threads and synchronization of shared variables
Tasks can be submitted to EventLoop
EventLoop tasks
• EventLoop indirectly extends Java’s ScheduledExecutorService
• Events and Tasks are executed in order received
• You can use ScheduledExecutorService methods to schedule a task
for later execution
• Tasks will run in same thread as IO so no sync needed
Use event loop to schedule tasks
EventLoop task schedule
ScheduledFuture<?> future =
channel.eventLoop().scheduleAtFixedRate(...);
Netty does task management to make sure only one thread can handle IO
Ensure Channel is handled by ONE Thread
• Any Thread can call methods on a Channel
• No synchronization in is needed
• How?
• If you call a method on a Channel and its not from the IO Thread (EventLoop thread)
• Netty will schedule a task for that method to be run and the task will run in EventLoop thread
• “Netty’s threading model hinges on determining the identity of the currently executing Thread; that is, whether or not
it is the one assigned to the current Channel and its EventLoop.” (Netty in Action)
• If method call is from EventLoop Thread, then method is executed right away
• Each EventLoop has a task queue
• task queue is not shared
• Do not put long running tasks in the task queue of an event loop
• If long running use another thread pool (not Netty) to execute and then call channel when done
Relationship for NIO
For NIO
• An EventLoop manages many Channels
• Channels can be sockets/connections/clients
• If you block in one, you block all clients
• Do not block
THANKS AND BUY
NORMAN’S BOOK
Netty in Action
Ideas for slides
• Many ideas for slides are directly derived from Netty
in Action book by Norman et al and/or his talks on
Netty
• BUY THE BOOK Netty in Action!
• The slides are a study aid for myself so I can better
learn Netty
• I’ve worked with ByteBuffer, NIO, Vert.x, and have
often wanted to use parts of Netty on projects but
lacked the knowledge of Netty internals so used NIO
or ByteBuffer or OIO when I really wanted to use
Netty instead
Previous slide deck
Previous SLIDE DECK
• Notes on Netty Basics Slideshare
• Part 1:
http://www.slideshare.net/richardhig
htower/notes-on-netty-baics
• Part 2:
http://www.slideshare.net/richardh
ightower/netty-notes-part-2-
transports-and-buffers
• Notes on Netty Basics Google slides
• Part 1: https://goo.gl/aUGm2N
• Part 2: https://goo.gl/xZZhVs
About Rick hightower
About Rick
• Implemented Microservices, Vert.x/Netty at massive scale
• Author of QBit, microservices lib and Boon, Json parser and utility lib
• Founder of Mammatus Technology
• Rick’s Twitter, Rick’s LinkedIn, Rick’s Blog, Rick’s Slideshare
The end… sleepless dev.

More Related Content

PPTX
Wiresharkの解析プラグインを作る ssmjp 201409
PDF
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
PPTX
Kubernetes サーバレス知識ゼロのエンジニアがKnative環境構築してみた
PDF
雑なMySQLパフォーマンスチューニング
PDF
InnoDB Locking Explained with Stick Figures
PDF
エキスパートPythonプログラミング改訂3版の読みどころ
PDF
DoS and DDoS mitigations with eBPF, XDP and DPDK
PDF
Apigee の FAPI & CIBA 対応を実現する「Authlete (オースリート)」
Wiresharkの解析プラグインを作る ssmjp 201409
Kafka for Microservices – You absolutely need Avro Schemas! | Gerardo Gutierr...
Kubernetes サーバレス知識ゼロのエンジニアがKnative環境構築してみた
雑なMySQLパフォーマンスチューニング
InnoDB Locking Explained with Stick Figures
エキスパートPythonプログラミング改訂3版の読みどころ
DoS and DDoS mitigations with eBPF, XDP and DPDK
Apigee の FAPI & CIBA 対応を実現する「Authlete (オースリート)」

What's hot (20)

PDF
Oracle database performance tuning
PPTX
The falco technical coaching framework
PDF
SFUの話
PPTX
pgday.seoul 2019: TimescaleDB
PDF
Yahoo!ニュースにおけるBFFパフォーマンスチューニング事例
PPTX
P4によるデータプレーンプログラミングとユースケースのご紹介
PDF
基本に戻ってInnoDBの話をします
PDF
Oracle Database performance tuning using oratop
PDF
Zaim 500万ユーザに向けて〜Aurora 編〜
PDF
How to run P4 BMv2
PDF
分割と整合性と戦う
PPTX
Introducing FIDO Device Onboard (FDO)
PDF
MyBatisとMyBatis Generatorの話
PDF
FreeSWITCH on Docker
PPTX
LINEのMySQL運用について 修正版
PDF
Dockerセキュリティ: 今すぐ役に立つテクニックから,次世代技術まで
PDF
Cephのベンチマークをしました
PDF
コンテナセキュリティにおける権限制御(OCHaCafe5 #3 Kubernetes のセキュリティ 発表資料)
PDF
Dockerイメージ管理の内部構造
PDF
An Architectural Deep Dive With Kubernetes And Containers Powerpoint Presenta...
Oracle database performance tuning
The falco technical coaching framework
SFUの話
pgday.seoul 2019: TimescaleDB
Yahoo!ニュースにおけるBFFパフォーマンスチューニング事例
P4によるデータプレーンプログラミングとユースケースのご紹介
基本に戻ってInnoDBの話をします
Oracle Database performance tuning using oratop
Zaim 500万ユーザに向けて〜Aurora 編〜
How to run P4 BMv2
分割と整合性と戦う
Introducing FIDO Device Onboard (FDO)
MyBatisとMyBatis Generatorの話
FreeSWITCH on Docker
LINEのMySQL運用について 修正版
Dockerセキュリティ: 今すぐ役に立つテクニックから,次世代技術まで
Cephのベンチマークをしました
コンテナセキュリティにおける権限制御(OCHaCafe5 #3 Kubernetes のセキュリティ 発表資料)
Dockerイメージ管理の内部構造
An Architectural Deep Dive With Kubernetes And Containers Powerpoint Presenta...
Ad

Similar to Netty Notes Part 3 - Channel Pipeline and EventLoops (20)

PPTX
Notes on Netty baics
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
PPTX
Tech talk microservices debugging
PPTX
Debugging Microservices - key challenges and techniques - Microservices Odesa...
PPTX
Scheduling Thread
PDF
SCaLE 16x - Application Monitoring And Tracing In Kubernetes
PDF
Janus/HOMER/HEPIC @ OpenSIPS18
PPT
Neutrondev ppt
PDF
Data Pipelines with Python - NWA TechFest 2017
PPTX
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
PPTX
Events for JavaScript event loop track.pptx
PDF
Ratpack Web Framework
PDF
Tupperware: Containerized Deployment at FB
ZIP
How we use Twisted in Launchpad
PDF
Writing Asynchronous Programs with Scala & Akka
PPTX
Building a document signing workflow with Durable Functions
PPT
Uklug2012 yellow and blue stream
PDF
FreeSWITCH as a Microservice
PPTX
Building a document e-signing workflow with Azure Durable Functions
Notes on Netty baics
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Tech talk microservices debugging
Debugging Microservices - key challenges and techniques - Microservices Odesa...
Scheduling Thread
SCaLE 16x - Application Monitoring And Tracing In Kubernetes
Janus/HOMER/HEPIC @ OpenSIPS18
Neutrondev ppt
Data Pipelines with Python - NWA TechFest 2017
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Events for JavaScript event loop track.pptx
Ratpack Web Framework
Tupperware: Containerized Deployment at FB
How we use Twisted in Launchpad
Writing Asynchronous Programs with Scala & Akka
Building a document signing workflow with Durable Functions
Uklug2012 yellow and blue stream
FreeSWITCH as a Microservice
Building a document e-signing workflow with Azure Durable Functions
Ad

More from Rick Hightower (19)

PDF
JParse Fast JSON Parser
PDF
Service Mesh Talk for CTO Forum
PPTX
Service Mesh CTO Forum (Draft 3)
PDF
Accelerate Delivery: Business Case for Agile DevOps, CI/CD and Microservices
PPTX
Accelerate Delivery: Business case for Agile DevOps, CI/CD and Microservices
PPTX
Accelerate DevOps/Microservices and Kubernetes
PPTX
Accelerate using DevOps and CI/CD.
PPTX
High-speed, Reactive Microservices 2017
PPTX
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
PPTX
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
PPTX
High-Speed Reactive Microservices - trials and tribulations
PDF
High-Speed Reactive Microservices
PPTX
Netty Notes Part 2 - Transports and Buffers
PPTX
WebSocket MicroService vs. REST Microservice
PDF
Consul: Microservice Enabling Microservices and Reactive Programming
PDF
The Java Microservice Library
PPTX
Java JSON Benchmark
PPT
MongoDB quickstart for Java, PHP, and Python developers
PPT
Mongo DB for Java, Python and PHP Developers
JParse Fast JSON Parser
Service Mesh Talk for CTO Forum
Service Mesh CTO Forum (Draft 3)
Accelerate Delivery: Business Case for Agile DevOps, CI/CD and Microservices
Accelerate Delivery: Business case for Agile DevOps, CI/CD and Microservices
Accelerate DevOps/Microservices and Kubernetes
Accelerate using DevOps and CI/CD.
High-speed, Reactive Microservices 2017
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
High-Speed Reactive Microservices - trials and tribulations
High-Speed Reactive Microservices
Netty Notes Part 2 - Transports and Buffers
WebSocket MicroService vs. REST Microservice
Consul: Microservice Enabling Microservices and Reactive Programming
The Java Microservice Library
Java JSON Benchmark
MongoDB quickstart for Java, PHP, and Python developers
Mongo DB for Java, Python and PHP Developers

Recently uploaded (20)

PDF
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
PDF
Child-friendly e-learning for artificial intelligence education in Indonesia:...
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PDF
Applying Agentic AI in Enterprise Automation
PDF
Revolutionizing recommendations a survey: a comprehensive exploration of mode...
PDF
Secure Java Applications against Quantum Threats
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PDF
TicketRoot: Event Tech Solutions Deck 2025
PPTX
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
PDF
Peak of Data & AI Encore: Scalable Design & Infrastructure
PPTX
CRM(Customer Relationship Managmnet) Presentation
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
PPTX
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
PDF
Altius execution marketplace concept.pdf
PPTX
maintenance powerrpoint for adaprive and preventive
PDF
Human Computer Interaction Miterm Lesson
PPTX
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
PDF
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
Child-friendly e-learning for artificial intelligence education in Indonesia:...
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
Applying Agentic AI in Enterprise Automation
Revolutionizing recommendations a survey: a comprehensive exploration of mode...
Secure Java Applications against Quantum Threats
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
TicketRoot: Event Tech Solutions Deck 2025
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
Peak of Data & AI Encore: Scalable Design & Infrastructure
CRM(Customer Relationship Managmnet) Presentation
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
Altius execution marketplace concept.pdf
maintenance powerrpoint for adaprive and preventive
Human Computer Interaction Miterm Lesson
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx

Netty Notes Part 3 - Channel Pipeline and EventLoops

  • 1. NOTES ON NETTY PART 3 RICK HIGHTOWER’S CHANNEL PIPELINES, AND EVENT LOOPS
  • 2. About Rick hightower About Rick • Implemented Microservices, Vert.x/Netty at massive scale • Author of QBit, microservices lib and Boon, Json parser and utility lib • Founder of Mammatus Technology • Rick’s Twitter, Rick’s LinkedIn, Rick’s Blog, Rick’s Slideshare
  • 3. Great book on Netty! https://www.manning.com/books/netty-in- action
  • 4. Great talk about Netty Best Practices given at Facebook, then Twitter University https://goo.gl/LbXheq
  • 6. Previous slide deck Previous SLIDE DECK • Notes on Netty Basics Slideshare • Part 1: http://www.slideshare.net/richardhig htower/notes-on-netty-baics • Part 2: http://www.slideshare.net/richardh ightower/netty-notes-part-2- transports-and-buffers • Notes on Netty Basics Google slides • Part 1: https://goo.gl/aUGm2N • Part 2: https://goo.gl/xZZhVs
  • 8. Chaining channel handlers ChannelPipeline • Channel - Socket • ByteBuf - container for bytes of message • ChannelHandler process / transform messages • ChannelPipeline - forms chain of ChannelHandlers
  • 9. Lifecycle of a channel Channel Lifecycle states • Active • connected to remote peer • Inactive • disconnected from remote peer • Unregistered • created • Registered • channel associated with event loop
  • 10. methods on ChannelHandler for lifecycle event ChannelHandler Lifecycle Events • handlerAdded() • added to ChannelPipeline • handlerRemoved() • removed from ChannelPipeline • exceptionCaught() • error during ChannelPipeline processing
  • 11. event notification event methods for ChannelInboundHander ChannelInboundHandler lifecycle methods for Channel • channelRegistered() - Channel married to an event loop • channelUnregistered() - Channel divorced from event loop • channelActive() - connected • channelInactive() - disconnected • channelReadComplete() - read operation completed • channelRead() - data is read on channel • channelWritabilityChanged() - outgoing IO buffer/limit is met or not • userEventTriggered() - someone passed a POJO to the event loop
  • 12. Let it go. Let it go. Can't hold it back anymore Releasing messages • Not a good idea to override read unless you know what you are doing • you must free up pooled resources calling ReferenceCountUtil.release(messag e) • Use SimpleChannelInboundHandler and override channelRead0() instead, netty will free up message resource for you java -Dio.netty.leakDetectionLevel=ADVANCED You can leak on write or read
  • 13. Handler for outbound ChannelOutboundHandler • Outbound operations • methods invoked by • Channel, ChannelPipeline, and ChannelHandlerContext. • Can defer operation or event • Powerful level of control • Many Methods take a ChannelPromise which extends ChannelFuture and provides ability to mark as succeeded or failed (setSuccess(), setFailure()) • You should mark promise failed or succeeded and also release resources
  • 14. lifecycle event methods ChannelOutboundHandler • bind(channelHandlerContext, localSocketAddress, channelPromise) • listen to address for connections request event • connect(channelHandlerContext, socketAddress, channelPromise) • connect to remote peer request event • disconnect(channelHandlerContext, channelPromise) • disconnect from remote peer request event • close(channelHandlerContext, channelPromise) • close channel request event
  • 15. lifecycle event methods ChannelOutboundHandler • deregister(channelHandlerContext, channelPromise) • removed from event loop request event • read(channelHandlerContext) • read more data from channel request event • flush(channelHandlerContext) • flush data to remote peer request event • write(channelHandlerContext, message:Object, channelPromise) • write data to channel request event
  • 16. chain of channel handlers ChannelPipeline • ChannelPipeline is chain of ChannelHandlers • handlers intercept inbound and outbound events through Channel • ChannelHandlers process application IO data • Channel processes IO events • New Channel assigned to new ChannelPipeline • relationship is permanent • no cheating! Channel can’t attach to another ChannelPipeline • Channel can’t leave ChannelPipeline • Direction determines if event handled by ChannelInboundHandler or a ChannelOutboundHandler • Unhanded events go to next Channel in chain
  • 17. ChannelHandlers can modify ChannelPipeline ChannelPipeline can be edited • ChannelHandler methods to change ChannelPipeline • addFirst() • addBefore() • addAfter() • addLast() • remove() • replace()
  • 18. Used by Netty to fire events inbound ChannelPipeline methods • fireChannelRegistered • fireChannelUnregistered • fireChannelActive • fireChannelInactive • fireExceptionCaught • fireUserEventTriggered - user defined event so you can pass a POJO to the channel • fireChannelRead • fireChannelReadComplete
  • 19. Outbound methods ChannelPipeline methods • bind - listen to a port, binds channel to port/address • connect - connect to a remote address • disconnect - disconnect from a remote address • close - close the channel after next channel handler is called • deregister • flush • write • writeAndFlush • read
  • 20. Managing passing the events to next handler in chain ChannelHandlerContext • Associates ChannelHandler and ChannelPipeline • Created when ChannelHandler added to a ChannelPipeline • Manages interaction of its ChannelHandler to others in ChannelPipeline • Use context instead of pipeline (most often) as it involves a shorter event flow • otherwise must go through whole chain from start
  • 21. Methods ChannelHandlerContext • channel - returns the Channel • bind, close, connect, disconnect • read, write • deregister • executor - returns EventExecutor (has thread pool scheduling interface) • fireChannelActive, fireChannelInactive, fireChannelRead, fireChannelReadComplete • handler - returns corresponding handler • isRemoved - has the handler been removed? • name - name of the instance • pipeline - returns the associated pipeline
  • 22. In Bound Exception handling public class MyInboundExceptionHandler extends ChannelInboundHandlerAdapter { … @Override public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) { logger.error(cause); channelHandlerContext.close(); } }
  • 23. Outbound Exception handling public class MyHandler extends ChannelOutboundHandlerAdapter { @Override public void write( final ChannelHandlerContext channelHandlerContext, final Object message, final ChannelPromise channelPromise) { channelPromise.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture channelFuture) { if (!channelFuture.isSuccess()) { logger.error(channelFuture.cause()); channelFuture.channel().close(); } } }); } }
  • 25. Threading model specifics Event Loop And Threading model • Threading model specifies is key to understanding Netty • When threads are spawned is very important to your application code • You have to understand trade-offs and specifics of Netty • Multi cores are common occurrence • Netty uses Executor API interfaces to schedule EventLoop tasks • Netty tries to reduce cost of thread hand off and CPU cache line moving about by limiting the #of threads to handle IO • Less is more by reducing “context switching" • Increases CPU Register, L1, L2, cache hits by keeping things in same thread • Reduce wake up cost of threads and synchronization of shared variables
  • 26. Tasks can be submitted to EventLoop EventLoop tasks • EventLoop indirectly extends Java’s ScheduledExecutorService • Events and Tasks are executed in order received • You can use ScheduledExecutorService methods to schedule a task for later execution • Tasks will run in same thread as IO so no sync needed
  • 27. Use event loop to schedule tasks EventLoop task schedule ScheduledFuture<?> future = channel.eventLoop().scheduleAtFixedRate(...);
  • 28. Netty does task management to make sure only one thread can handle IO Ensure Channel is handled by ONE Thread • Any Thread can call methods on a Channel • No synchronization in is needed • How? • If you call a method on a Channel and its not from the IO Thread (EventLoop thread) • Netty will schedule a task for that method to be run and the task will run in EventLoop thread • “Netty’s threading model hinges on determining the identity of the currently executing Thread; that is, whether or not it is the one assigned to the current Channel and its EventLoop.” (Netty in Action) • If method call is from EventLoop Thread, then method is executed right away • Each EventLoop has a task queue • task queue is not shared • Do not put long running tasks in the task queue of an event loop • If long running use another thread pool (not Netty) to execute and then call channel when done
  • 29. Relationship for NIO For NIO • An EventLoop manages many Channels • Channels can be sockets/connections/clients • If you block in one, you block all clients • Do not block
  • 31. Netty in Action Ideas for slides • Many ideas for slides are directly derived from Netty in Action book by Norman et al and/or his talks on Netty • BUY THE BOOK Netty in Action! • The slides are a study aid for myself so I can better learn Netty • I’ve worked with ByteBuffer, NIO, Vert.x, and have often wanted to use parts of Netty on projects but lacked the knowledge of Netty internals so used NIO or ByteBuffer or OIO when I really wanted to use Netty instead
  • 32. Previous slide deck Previous SLIDE DECK • Notes on Netty Basics Slideshare • Part 1: http://www.slideshare.net/richardhig htower/notes-on-netty-baics • Part 2: http://www.slideshare.net/richardh ightower/netty-notes-part-2- transports-and-buffers • Notes on Netty Basics Google slides • Part 1: https://goo.gl/aUGm2N • Part 2: https://goo.gl/xZZhVs
  • 33. About Rick hightower About Rick • Implemented Microservices, Vert.x/Netty at massive scale • Author of QBit, microservices lib and Boon, Json parser and utility lib • Founder of Mammatus Technology • Rick’s Twitter, Rick’s LinkedIn, Rick’s Blog, Rick’s Slideshare The end… sleepless dev.