SlideShare a Scribd company logo
Asynchronous, Event-driven
Network Application Development
with Netty
Rapid development of maintainable high performance protocol servers & clients
Ankara JUG, June 2015
Ersin Er - @ersiner
About the speaker, Ersin Er
Summary of what’s on LinkedIn
● Computer Sci. Student @ Hacettepe Univ. - BSc (’03), MSc (’06), PhD (~)
● Teaching Assistant [and System Admin.] @ Hacettepe Univ. (’03-’11)
● Committer and PMC Member @ Apache Software Foundation (’05-’10)
● Software Architect @ Peak Games (’11-’13)
● Co-founder and Solutions Architect @ Metasolid (’14-’15)
● Hands-on Solutions and Software Architect.
● Distributed Systems, Concurrency and Performance Programming
enthusiast.
● Does tech biz, manages projects, deals with people.
● Used to be a perfectionist. Does not produce garbage.
How to name your presentation
Today’s Agenda
● Blocking vs Non-Blocking I/O
● NIO and Netty Abstractions
● What sets Netty apart
● Netty Reusables
● Netty & HTTP
● Servlet 3.0 and 3.1 (for our beloved JavaEE friends )
● Netty Ecosystem
Do not expect a 1-1
matched flow with
these titles.
I prefer discussions to
static information
dumping.
Let’s review
Blocking Socket I/O in Java
by examples
in order to steer
our discussions on
Non-Blocking I/O,
Java NIO
and Netty.
Blocking I/O Socket Server Example
Single Client, Single Request
public static void serve1() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
Socket clientSocket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
if ((request = in.readLine()) != null) {
response = request + " processed at " + new Date();
out.println(response);
}
in.close();
out.close();
}
Protocol
Implementation
Blocking I/O Socket Server Example
Single Client, Multi Request
public static void serve2() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
Socket clientSocket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
response = request + " processed at " + new Date();
out.println(response);
}
in.close();
out.close();
}
Wow!
That was
easy!
Blocking I/O Socket Server Example
Single Client, Multi Request, Client Exit Control
public static void serve3() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
Socket clientSocket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
if ("Exit".equals(request)) {
break;
}
response = request + " processed at " + new Date();
out.println(response);
}
in.close();
out.close();
}
More Protocol
Blocking I/O Socket Server Example
Multi Client, Multi Request, Client Exit Control
public static void serve4() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
while (true) {
Socket clientSocket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
if ("Exit".equals(request)) {
break;
}
response = request + " processed at " + new Date();
out.println(response);
}
in.close();
out.close();
}
}
A new generation ofInternet servicesupporting multipleusers?..
Blocking I/O Socket Server Example
Concurrent Clients, Multi Request, Client Exit Control
public static void serve5() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
while (true) {
final Socket clientSocket = serverSocket.accept();
new Thread() {
public void run() {
try {
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
if ("Exit".equals(request)) { break; }
response = request + " processed at " + new Date(); out.println(response);
}
in.close(); out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}.start();
}
}
!!!
These are far from
being production
code. In fact, they
are terrible ones.
Uncontrolled
Power!
Multi-Threaded Blocking I/O Exhausting Resources
What to do?
public static void serve5() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
while (true) {
final Socket clientSocket = serverSocket.accept();
new Thread() {
public void run() {
try {
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
if ("Exit".equals(request)) { break; }
response = request + " processed at " + new Date(); out.println(response);
}
in.close(); out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}.start();
}
}
!!!
These are far from
being production
code. In fact, they
are terrible ones.
Uncontrolled
Power!
What to do?
● Pooling?
● Executors?
● Queuing?
Multi-Threaded Blocking I/O Exhausting Resources
What to do? - Critical Discussion
public static void serve5() throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
while (true) {
final Socket clientSocket = serverSocket.accept();
new Thread() {
public void run() {
try {
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader in = new BufferedReader(isr);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request, response;
while ((request = in.readLine()) != null) {
if ("Exit".equals(request)) { break; }
response = request + " processed at " + new Date(); out.println(response);
}
in.close(); out.close();
} catch (IOException e) { e.printStackTrace(); }
}
}.start();
}
}
!!!
These are far from
being production
code. In fact, they
are terrible ones.
Uncontrolled
Power!
What to do?
● Pooling?
● Executors?
● Queuing?
The discussion here iscritical for switching(our minds) to Non-Blocking I/O, Java NIOand Netty
Asynchronous, Event-driven Network Application Development with Netty
Non-Blocking I/O
● Sockets in Non-Blocking Mode
● I/O Multiplexing
○ epoll (Linux)
○ kqueue (FreeBSD)
○ IOCP (Windows, Solaris)
● Single Thread for many sockets (or file
descriptors)
● Key to high performance servers
Non-Blocking or
Asynchronous?
(Blocking or Synchronous?)
Simplified definitions that can work for us today:
● Non-Blocking: No waiting for the operation
to complete
● Asynchronous: Notification upon completion
of non-blocking operation
Java NIO
● NIO = Non-Blocking I/O?
● It’s Java New I/O
● It’s no longer new (came with Java 1.4)
○ Java 7 comes with V2
● Not only for Socket I/O
● First Class Citizens
○ Channels
○ Buffers
○ Selectors
NIO - Channels and Buffers
● Channels
○ FileChannel
○ DatagramChannel
○ SocketChannel
○ ServerSocketChannel
● Buffers
○ ByteBuffer
○ CharBuffer
○ DoubleBuffer
○ FloatBuffer
○ IntBuffer
○ LongBuffer
○ ShortBuffer
● Data are read from
Channels into Buffers
● Data are written from
Buffers into Channels
NIO - Buffers are serious business
Buffer capacity, position and limit
in write and read mode.
Buffer.flip() makes the mode
change.
We also have:
● Heap Buffers
○ Array Based
○ ByteBuffer.allocate()
● Direct Buffers
○ Off-Heap
○ ByteBuffer.allocateDirect()
NIO - Selectors & I/O Multiplexing
OIO vs NIO
From NIO to Netty
Using NIO directly is like using
Naked Threads.
Netty replaces NIO APIs
with superiors and
provides incredible
capabilities.
Netty Core Components and Utilities
● Channels and Transports
● ByteBuf and Un/Pooled Allocation
Management
● ChannelHandlers and ChannelPipeline
● The Codec Framework and Reusable
Codecs
● Bootstraps and ChannelInitializers
● Futures and EventLoops
Channels and Transports
Package View
● io.netty.channel.embedded
● io.netty.channel.epoll
● io.netty.channel.local
● io.netty.channel.nio
● io.netty.channel.oio
● io.netty.channel.rxtx
● io.netty.channel.sctp
● io.netty.channel.sctp.nio
● io.netty.channel.sctp.oio
● io.netty.channel.socket
● io.netty.channel.socket.nio
● io.netty.channel.socket.oio
● io.netty.channel.udt
● io.netty.channel.udt.nio
● io.netty.channel.unix
● You can both read from write into Channels
(they are duplex as opposed to streams)
● All I/O operations on channels are
asynchronous and return listenable
futures
● Channels are implemented for various
Transports types:
○ Unified API for NIO and OID (and
others)
○ Epoll transport for extreme
performance
○ Local transport for in VM
communication
○ Embedded transport for Unit Testing
ByteBuf and Un/Pooled Allocation
Management
● ByteBuf is improved version of ByteBuffer
● ByteBuf has both write and read index, does not need
flip()
● CompositeByteBuf enables Zero-Copy
● ByteBufs can be pooled for reducing garbage collector
pressure
https://blog.twitter.com/2013/netty-4-at-twitter-reduced-gc-overhead
ChannelHandlers and ChannelPipeline
Channel
Inbound
Handler
Channel
Inbound
Handler
Channel
Outbound
Handler
Channel
Outbound
Handler
Head Tail
Socket
Channel
Pipeline
ChannelPipeline has been designed
with Intercepting Filter pattern and
resembles Servlet Filters
Codec Framework
● Simplified and focused API on top of
ChannelHandlers
● Decoders are ChannelInboundHandlers
● Encoders are ChannelOutboundHandlers
● Codecs are both CIH and COH
Reusable Codecs
● io.netty.handler.codec.base64
● io.netty.handler.codec.bytes
● io.netty.handler.codec.compression
● io.netty.handler.codec.haproxy
● io.netty.handler.codec.http
● io.netty.handler.codec.http.cookie
● io.netty.handler.codec.http.cors
● io.netty.handler.codec.http.multipart
● io.netty.handler.codec.http.websocketx
● io.netty.handler.codec.marshalling
● io.netty.handler.codec.protobuf
● io.netty.handler.codec.rtsp
● io.netty.handler.codec.sctp
● io.netty.handler.codec.serialization
● io.netty.handler.codec.socks
● io.netty.handler.codec.spdy
● io.netty.handler.codec.string
● io.netty.handler.logging
● io.netty.handler.ssl
● io.netty.handler.stream
● io.netty.handler.timeout
● io.netty.handler.traffic
● DelimiterBasedFrameDecoder
● LengthFieldBasedFrameDecoder
● FixedLengthFrameDecoder
● LineBasedFrameDecoder
Some primitive
ones
All of these
represent
patterns of
protocol
development
Bootstraps and
ChannelInitializers
Bootstraps help bootstrap
channels (server or client
side)
● Set EventLoopGroups
● Set ChannelHandlers
● Bind to Network
Interfaces
ChannelInitializer is a
special ChannelHandler
● Handles
channelRegistered
event and applies its
pipeline config to the
channel
● (Suggested: See its
source code)
Futures and EventLoops
● All I/O operations on Channels return listenable futures
● Each Channel is assigned to a single EventLoop and
stays so during its lifetime
● EventLoops handle all I/O operations of their Channels
● EventLoopGroups are like Thread Pools and number of
EventLoops they manage depends on number of CPU
cores (and possible other factors)
● Listeners registered to Futures are handled by
appropriate EventLoop selected by Netty
Now, Examples
Servlet
● Servlet 3.0 - Async Processing of Response
● Servlet 3.1 - Non-Blocking Processing of
Request (Content)
Did you expect more?
Come on, this is Netty :-)
Netty Versions
● 3.x Old, Stable
● 4.0.x Current, Stable
○ Huge improvements over 3.x
○ https://github.com/netty/netty/wiki/New-and-noteworthy-in-4.0
● 4.1 Beta (Close to be Stable)
○ Mostly backward compatible with 4.0
○ Android support and lots of new codecs
○ https://github.com/netty/netty/wiki/New-and-noteworthy-in-4.1
● 5.0 Alpha - Backward Incompatible Improvements
○ https://github.com/netty/netty/wiki/New-and-noteworthy-in-5.0
Ecosystem - Related Projects
(The ones I’ve been interested in and mostly using Netty at its heart)
● Vert.x - A toolkit for building reactive applications on the JVM
● Ratpack - Simple, lean & powerful HTTP apps
● async-http-client - Asynchronous Http and WebSocket Client
library for Java
● RxNetty - Reactive Extension (Rx) Adaptor for Netty
● nettosphere - A Java WebSocket/HTTP server based on the
Atmosphere and Netty Framework
● grpc-java - The Java gRPC implementation (by Google)
● Play Framework - The High Velocity Web Framework For Java and
Scala
● More at http://netty.io/wiki/related-projects.html and http://netty.
io/wiki/adopters.html
Ecosystem - Resources
● Netty Documentation & Examples
○ http://netty.io/wiki/index.html
● StackOverflow
○ http://stackoverflow.com/questions/tagged/netty
● Netty in Action
○ http://www.manning.com/maurer/
Thanks
● You, attenders!
● Ankara JUG organizers, for having me here
● Jakob Jenkov, for allowing me use his diagrams for
explaining NIO Concepts (http://tutorials.jenkov.
com/java-nio/index.html)
Ad

Recommended

Spring boot introduction
Spring boot introduction
Rasheed Waraich
 
Building Netty Servers
Building Netty Servers
Dani SolĂ  Lagares
 
Hydra: A Vocabulary for Hypermedia-Driven Web APIs
Hydra: A Vocabulary for Hypermedia-Driven Web APIs
Markus Lanthaler
 
Building Next-Generation Web APIs with JSON-LD and Hydra
Building Next-Generation Web APIs with JSON-LD and Hydra
Markus Lanthaler
 
I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't one
Adrian Cole
 
Introduction to spring boot
Introduction to spring boot
Santosh Kumar Kar
 
Node.js Express Framework
Node.js Express Framework
TheCreativedev Blog
 
Spring boot
Spring boot
Gyanendra Yadav
 
Intro to React
Intro to React
Justin Reock
 
JSON-LD for RESTful services
JSON-LD for RESTful services
Markus Lanthaler
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Spring Framework
Spring Framework
tola99
 
Distributed Locking in Kubernetes
Distributed Locking in Kubernetes
RafaƂ Leszko
 
Spring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
Box Model
Box Model
Amit Kumar Singh
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
What Is Express JS?
What Is Express JS?
Simplilearn
 
Apache cassandra v4.0
Apache cassandra v4.0
Yuki Morishita
 
InfluxDB 101 - Concepts and Architecture | Michael DeSa | InfluxData
InfluxDB 101 - Concepts and Architecture | Michael DeSa | InfluxData
InfluxData
 
Java servlets
Java servlets
lopjuan
 
Spring Boot
Spring Boot
Jiayun Zhou
 
Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Introduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
JSON-LD and MongoDB
JSON-LD and MongoDB
Gregg Kellogg
 
How to Build an Apache KafkaÂź Connector
How to Build an Apache KafkaÂź Connector
confluent
 
Apache Flink and what it is used for
Apache Flink and what it is used for
Aljoscha Krettek
 
Ajax presentation
Ajax presentation
engcs2008
 
Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
JJUG CCC 2018 Spring - I-7 (äżșが)はじめどぼ Netty
JJUG CCC 2018 Spring - I-7 (äżșが)はじめどぼ Netty
Shinya Mochida
 
Netty: asynchronous data transfer
Netty: asynchronous data transfer
Victor Cherkassky
 

More Related Content

What's hot (20)

Intro to React
Intro to React
Justin Reock
 
JSON-LD for RESTful services
JSON-LD for RESTful services
Markus Lanthaler
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Spring Framework
Spring Framework
tola99
 
Distributed Locking in Kubernetes
Distributed Locking in Kubernetes
RafaƂ Leszko
 
Spring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
Box Model
Box Model
Amit Kumar Singh
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
What Is Express JS?
What Is Express JS?
Simplilearn
 
Apache cassandra v4.0
Apache cassandra v4.0
Yuki Morishita
 
InfluxDB 101 - Concepts and Architecture | Michael DeSa | InfluxData
InfluxDB 101 - Concepts and Architecture | Michael DeSa | InfluxData
InfluxData
 
Java servlets
Java servlets
lopjuan
 
Spring Boot
Spring Boot
Jiayun Zhou
 
Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Introduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
JSON-LD and MongoDB
JSON-LD and MongoDB
Gregg Kellogg
 
How to Build an Apache KafkaÂź Connector
How to Build an Apache KafkaÂź Connector
confluent
 
Apache Flink and what it is used for
Apache Flink and what it is used for
Aljoscha Krettek
 
Ajax presentation
Ajax presentation
engcs2008
 
Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
Intro to React
Intro to React
Justin Reock
 
JSON-LD for RESTful services
JSON-LD for RESTful services
Markus Lanthaler
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Spring Framework
Spring Framework
tola99
 
Distributed Locking in Kubernetes
Distributed Locking in Kubernetes
RafaƂ Leszko
 
Spring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
What Is Express JS?
What Is Express JS?
Simplilearn
 
Apache cassandra v4.0
Apache cassandra v4.0
Yuki Morishita
 
InfluxDB 101 - Concepts and Architecture | Michael DeSa | InfluxData
InfluxDB 101 - Concepts and Architecture | Michael DeSa | InfluxData
InfluxData
 
Java servlets
Java servlets
lopjuan
 
Spring Boot
Spring Boot
Jiayun Zhou
 
Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Introduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
JSON-LD and MongoDB
JSON-LD and MongoDB
Gregg Kellogg
 
How to Build an Apache KafkaÂź Connector
How to Build an Apache KafkaÂź Connector
confluent
 
Apache Flink and what it is used for
Apache Flink and what it is used for
Aljoscha Krettek
 
Ajax presentation
Ajax presentation
engcs2008
 
Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 

Similar to Asynchronous, Event-driven Network Application Development with Netty (20)

JJUG CCC 2018 Spring - I-7 (äżșが)はじめどぼ Netty
JJUG CCC 2018 Spring - I-7 (äżșが)はじめどぼ Netty
Shinya Mochida
 
Netty: asynchronous data transfer
Netty: asynchronous data transfer
Victor Cherkassky
 
Java nio ( new io )
Java nio ( new io )
Jemin Patel
 
Netty from the trenches
Netty from the trenches
Jordi Gerona
 
Rapid Network Application Development with Apache MINA
Rapid Network Application Development with Apache MINA
trustinlee
 
Scalable io in java
Scalable io in java
Giridhar Addepalli
 
Non blocking io with netty
Non blocking io with netty
Zauber
 
Building High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINA
elliando dias
 
Nio
Nio
nextlib
 
A java servers
A java servers
vibrantuser
 
A java servers
A java servers
vibrantuser
 
MINA2 (Apache Netty)
MINA2 (Apache Netty)
ducquoc_vn
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
arccreation001
 
High performance network programming on the jvm oscon 2012
High performance network programming on the jvm oscon 2012
Erik Onnen
 
16network Programming Servers
16network Programming Servers
Adil Jafri
 
Socket Programming in Java.ppt yeh haii
Socket Programming in Java.ppt yeh haii
inambscs4508
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 
Developing high-performance network servers in Lisp
Developing high-performance network servers in Lisp
Vladimir Sedach
 
Java networking programs - theory
Java networking programs - theory
Mukesh Tekwani
 
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Harold Elliotte
zubinrlondoit
 
JJUG CCC 2018 Spring - I-7 (äżșが)はじめどぼ Netty
JJUG CCC 2018 Spring - I-7 (äżșが)はじめどぼ Netty
Shinya Mochida
 
Netty: asynchronous data transfer
Netty: asynchronous data transfer
Victor Cherkassky
 
Java nio ( new io )
Java nio ( new io )
Jemin Patel
 
Netty from the trenches
Netty from the trenches
Jordi Gerona
 
Rapid Network Application Development with Apache MINA
Rapid Network Application Development with Apache MINA
trustinlee
 
Non blocking io with netty
Non blocking io with netty
Zauber
 
Building High Performance Scalable TCP/IP Servers with Apache MINA
Building High Performance Scalable TCP/IP Servers with Apache MINA
elliando dias
 
Nio
Nio
nextlib
 
A java servers
A java servers
vibrantuser
 
A java servers
A java servers
vibrantuser
 
MINA2 (Apache Netty)
MINA2 (Apache Netty)
ducquoc_vn
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
arccreation001
 
High performance network programming on the jvm oscon 2012
High performance network programming on the jvm oscon 2012
Erik Onnen
 
16network Programming Servers
16network Programming Servers
Adil Jafri
 
Socket Programming in Java.ppt yeh haii
Socket Programming in Java.ppt yeh haii
inambscs4508
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 
Developing high-performance network servers in Lisp
Developing high-performance network servers in Lisp
Vladimir Sedach
 
Java networking programs - theory
Java networking programs - theory
Mukesh Tekwani
 
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Harold Elliotte
zubinrlondoit
 
Ad

Recently uploaded (20)

Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
grete1122g
 
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
Why Edge Computing Matters in Mobile Application Tech.pdf
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
NEW-IDM Crack with Internet Download Manager 6.42 Build 27 VERSION
grete1122g
 
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
From Code to Commerce, a Backend Java Developer's Galactic Journey into Ecomm...
Jamie Coleman
 
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
On-Device AI: Is It Time to Go All-In, or Do We Still Need the Cloud?
Hassan Abid
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Microsoft-365-Administrator-s-Guide1.pdf
Microsoft-365-Administrator-s-Guide1.pdf
mazharatknl
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
Top Time Tracking Solutions for Accountants
Top Time Tracking Solutions for Accountants
oliviareed320
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Ad

Asynchronous, Event-driven Network Application Development with Netty

  • 1. Asynchronous, Event-driven Network Application Development with Netty Rapid development of maintainable high performance protocol servers & clients Ankara JUG, June 2015 Ersin Er - @ersiner
  • 2. About the speaker, Ersin Er Summary of what’s on LinkedIn ● Computer Sci. Student @ Hacettepe Univ. - BSc (’03), MSc (’06), PhD (~) ● Teaching Assistant [and System Admin.] @ Hacettepe Univ. (’03-’11) ● Committer and PMC Member @ Apache Software Foundation (’05-’10) ● Software Architect @ Peak Games (’11-’13) ● Co-founder and Solutions Architect @ Metasolid (’14-’15) ● Hands-on Solutions and Software Architect. ● Distributed Systems, Concurrency and Performance Programming enthusiast. ● Does tech biz, manages projects, deals with people. ● Used to be a perfectionist. Does not produce garbage.
  • 3. How to name your presentation
  • 4. Today’s Agenda ● Blocking vs Non-Blocking I/O ● NIO and Netty Abstractions ● What sets Netty apart ● Netty Reusables ● Netty & HTTP ● Servlet 3.0 and 3.1 (for our beloved JavaEE friends ) ● Netty Ecosystem Do not expect a 1-1 matched flow with these titles. I prefer discussions to static information dumping.
  • 5. Let’s review Blocking Socket I/O in Java by examples in order to steer our discussions on Non-Blocking I/O, Java NIO and Netty.
  • 6. Blocking I/O Socket Server Example Single Client, Single Request public static void serve1() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); Socket clientSocket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; if ((request = in.readLine()) != null) { response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } Protocol Implementation
  • 7. Blocking I/O Socket Server Example Single Client, Multi Request public static void serve2() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); Socket clientSocket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; while ((request = in.readLine()) != null) { response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } Wow! That was easy!
  • 8. Blocking I/O Socket Server Example Single Client, Multi Request, Client Exit Control public static void serve3() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); Socket clientSocket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; while ((request = in.readLine()) != null) { if ("Exit".equals(request)) { break; } response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } More Protocol
  • 9. Blocking I/O Socket Server Example Multi Client, Multi Request, Client Exit Control public static void serve4() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); while (true) { Socket clientSocket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; while ((request = in.readLine()) != null) { if ("Exit".equals(request)) { break; } response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } } A new generation ofInternet servicesupporting multipleusers?..
  • 10. Blocking I/O Socket Server Example Concurrent Clients, Multi Request, Client Exit Control public static void serve5() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); while (true) { final Socket clientSocket = serverSocket.accept(); new Thread() { public void run() { try { InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; while ((request = in.readLine()) != null) { if ("Exit".equals(request)) { break; } response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } } !!! These are far from being production code. In fact, they are terrible ones. Uncontrolled Power!
  • 11. Multi-Threaded Blocking I/O Exhausting Resources What to do? public static void serve5() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); while (true) { final Socket clientSocket = serverSocket.accept(); new Thread() { public void run() { try { InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; while ((request = in.readLine()) != null) { if ("Exit".equals(request)) { break; } response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } } !!! These are far from being production code. In fact, they are terrible ones. Uncontrolled Power! What to do? ● Pooling? ● Executors? ● Queuing?
  • 12. Multi-Threaded Blocking I/O Exhausting Resources What to do? - Critical Discussion public static void serve5() throws IOException { ServerSocket serverSocket = new ServerSocket(10000); while (true) { final Socket clientSocket = serverSocket.accept(); new Thread() { public void run() { try { InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream()); BufferedReader in = new BufferedReader(isr); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String request, response; while ((request = in.readLine()) != null) { if ("Exit".equals(request)) { break; } response = request + " processed at " + new Date(); out.println(response); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } } !!! These are far from being production code. In fact, they are terrible ones. Uncontrolled Power! What to do? ● Pooling? ● Executors? ● Queuing? The discussion here iscritical for switching(our minds) to Non-Blocking I/O, Java NIOand Netty
  • 14. Non-Blocking I/O ● Sockets in Non-Blocking Mode ● I/O Multiplexing ○ epoll (Linux) ○ kqueue (FreeBSD) ○ IOCP (Windows, Solaris) ● Single Thread for many sockets (or file descriptors) ● Key to high performance servers
  • 15. Non-Blocking or Asynchronous? (Blocking or Synchronous?) Simplified definitions that can work for us today: ● Non-Blocking: No waiting for the operation to complete ● Asynchronous: Notification upon completion of non-blocking operation
  • 16. Java NIO ● NIO = Non-Blocking I/O? ● It’s Java New I/O ● It’s no longer new (came with Java 1.4) ○ Java 7 comes with V2 ● Not only for Socket I/O ● First Class Citizens ○ Channels ○ Buffers ○ Selectors
  • 17. NIO - Channels and Buffers ● Channels ○ FileChannel ○ DatagramChannel ○ SocketChannel ○ ServerSocketChannel ● Buffers ○ ByteBuffer ○ CharBuffer ○ DoubleBuffer ○ FloatBuffer ○ IntBuffer ○ LongBuffer ○ ShortBuffer ● Data are read from Channels into Buffers ● Data are written from Buffers into Channels
  • 18. NIO - Buffers are serious business Buffer capacity, position and limit in write and read mode. Buffer.flip() makes the mode change. We also have: ● Heap Buffers ○ Array Based ○ ByteBuffer.allocate() ● Direct Buffers ○ Off-Heap ○ ByteBuffer.allocateDirect()
  • 19. NIO - Selectors & I/O Multiplexing
  • 21. From NIO to Netty Using NIO directly is like using Naked Threads. Netty replaces NIO APIs with superiors and provides incredible capabilities.
  • 22. Netty Core Components and Utilities ● Channels and Transports ● ByteBuf and Un/Pooled Allocation Management ● ChannelHandlers and ChannelPipeline ● The Codec Framework and Reusable Codecs ● Bootstraps and ChannelInitializers ● Futures and EventLoops
  • 23. Channels and Transports Package View ● io.netty.channel.embedded ● io.netty.channel.epoll ● io.netty.channel.local ● io.netty.channel.nio ● io.netty.channel.oio ● io.netty.channel.rxtx ● io.netty.channel.sctp ● io.netty.channel.sctp.nio ● io.netty.channel.sctp.oio ● io.netty.channel.socket ● io.netty.channel.socket.nio ● io.netty.channel.socket.oio ● io.netty.channel.udt ● io.netty.channel.udt.nio ● io.netty.channel.unix ● You can both read from write into Channels (they are duplex as opposed to streams) ● All I/O operations on channels are asynchronous and return listenable futures ● Channels are implemented for various Transports types: ○ Unified API for NIO and OID (and others) ○ Epoll transport for extreme performance ○ Local transport for in VM communication ○ Embedded transport for Unit Testing
  • 24. ByteBuf and Un/Pooled Allocation Management ● ByteBuf is improved version of ByteBuffer ● ByteBuf has both write and read index, does not need flip() ● CompositeByteBuf enables Zero-Copy ● ByteBufs can be pooled for reducing garbage collector pressure https://blog.twitter.com/2013/netty-4-at-twitter-reduced-gc-overhead
  • 25. ChannelHandlers and ChannelPipeline Channel Inbound Handler Channel Inbound Handler Channel Outbound Handler Channel Outbound Handler Head Tail Socket Channel Pipeline ChannelPipeline has been designed with Intercepting Filter pattern and resembles Servlet Filters
  • 26. Codec Framework ● Simplified and focused API on top of ChannelHandlers ● Decoders are ChannelInboundHandlers ● Encoders are ChannelOutboundHandlers ● Codecs are both CIH and COH
  • 27. Reusable Codecs ● io.netty.handler.codec.base64 ● io.netty.handler.codec.bytes ● io.netty.handler.codec.compression ● io.netty.handler.codec.haproxy ● io.netty.handler.codec.http ● io.netty.handler.codec.http.cookie ● io.netty.handler.codec.http.cors ● io.netty.handler.codec.http.multipart ● io.netty.handler.codec.http.websocketx ● io.netty.handler.codec.marshalling ● io.netty.handler.codec.protobuf ● io.netty.handler.codec.rtsp ● io.netty.handler.codec.sctp ● io.netty.handler.codec.serialization ● io.netty.handler.codec.socks ● io.netty.handler.codec.spdy ● io.netty.handler.codec.string ● io.netty.handler.logging ● io.netty.handler.ssl ● io.netty.handler.stream ● io.netty.handler.timeout ● io.netty.handler.traffic ● DelimiterBasedFrameDecoder ● LengthFieldBasedFrameDecoder ● FixedLengthFrameDecoder ● LineBasedFrameDecoder Some primitive ones All of these represent patterns of protocol development
  • 28. Bootstraps and ChannelInitializers Bootstraps help bootstrap channels (server or client side) ● Set EventLoopGroups ● Set ChannelHandlers ● Bind to Network Interfaces ChannelInitializer is a special ChannelHandler ● Handles channelRegistered event and applies its pipeline config to the channel ● (Suggested: See its source code)
  • 29. Futures and EventLoops ● All I/O operations on Channels return listenable futures ● Each Channel is assigned to a single EventLoop and stays so during its lifetime ● EventLoops handle all I/O operations of their Channels ● EventLoopGroups are like Thread Pools and number of EventLoops they manage depends on number of CPU cores (and possible other factors) ● Listeners registered to Futures are handled by appropriate EventLoop selected by Netty
  • 31. Servlet ● Servlet 3.0 - Async Processing of Response ● Servlet 3.1 - Non-Blocking Processing of Request (Content) Did you expect more? Come on, this is Netty :-)
  • 32. Netty Versions ● 3.x Old, Stable ● 4.0.x Current, Stable ○ Huge improvements over 3.x ○ https://github.com/netty/netty/wiki/New-and-noteworthy-in-4.0 ● 4.1 Beta (Close to be Stable) ○ Mostly backward compatible with 4.0 ○ Android support and lots of new codecs ○ https://github.com/netty/netty/wiki/New-and-noteworthy-in-4.1 ● 5.0 Alpha - Backward Incompatible Improvements ○ https://github.com/netty/netty/wiki/New-and-noteworthy-in-5.0
  • 33. Ecosystem - Related Projects (The ones I’ve been interested in and mostly using Netty at its heart) ● Vert.x - A toolkit for building reactive applications on the JVM ● Ratpack - Simple, lean & powerful HTTP apps ● async-http-client - Asynchronous Http and WebSocket Client library for Java ● RxNetty - Reactive Extension (Rx) Adaptor for Netty ● nettosphere - A Java WebSocket/HTTP server based on the Atmosphere and Netty Framework ● grpc-java - The Java gRPC implementation (by Google) ● Play Framework - The High Velocity Web Framework For Java and Scala ● More at http://netty.io/wiki/related-projects.html and http://netty. io/wiki/adopters.html
  • 34. Ecosystem - Resources ● Netty Documentation & Examples ○ http://netty.io/wiki/index.html ● StackOverflow ○ http://stackoverflow.com/questions/tagged/netty ● Netty in Action ○ http://www.manning.com/maurer/
  • 35. Thanks ● You, attenders! ● Ankara JUG organizers, for having me here ● Jakob Jenkov, for allowing me use his diagrams for explaining NIO Concepts (http://tutorials.jenkov. com/java-nio/index.html)