SlideShare a Scribd company logo
1 of 22
Download to read offline
Java NIO.2
Network socket
Network socket is an endpoint of a connection across a computer network.
Main types of Internet socket:
● Datagram sockets, which use User Datagram Protocol (UDP).
● Stream sockets, which use Transmission Control Protocol (TCP) or Stream
Control Transmission Protocol (SCTP).
● Raw sockets, typically available in routers and other network equipment.
Java IO vs NIO
IO NIO
Stream-oriented Buffer-oriented
Blocking I/O Non-blocking I/O
Selectors
Channels
Java.IO - Stream-oriented
Data Source Program
Data
Destination Program
001001001111001001001001011
001001001111001001001001011
Java.IO - Blocking I/O
Socket Thread
read data, block until ready
read data, block until ready
write data, block until ready
write data, block until ready
Java.IO — Work with data
// read from socket
Scanner sc = new Scanner(socket.getInputStream());
String string = sc.nextLine();
System.out.println("Received " + string);
// write to socket
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("Hello");
Java.NIO — Buffer-oriented & Non-blocking I/O
Channel Buffer Thread
read data into buffer
fill data into buffer
check data in buffer
goto top
Java.NIO — Work with data
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// prepare to read
readBuffer.clear();
SocketChannel channel = getChannel();
channel.read(readBuffer);
readBuffer.flip();
// reading the buffer
// ...............…
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// prepare to put data
writeBuffer.clear();
// putting the data
// ...............
// prepare to write
writeBuffer.flip();
channel.write(writeBuffer);
Java.NIO — Selector & Channels
Channel is a lightweight entity effeciently
transporting data between sockets as a tube.
Selector is a manager allowing a single thread to
monitor multiple input channels.
Java.IO - Classic IO server design
Server
Socket
Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Java.NIO — NIO server design
Thread
Selector
Channel Channel Channel Channel
Java.NIO — NIO server design
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress("localhost", 2222));
channel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.select() == 0) {
Thread.sleep(1);
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (selectionKey.isConnectable()) {
// a connection was established with a remote.
} else if (selectionKey.isReadable()) {
// a channel is ready for reading
} else if (selectionKey.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
Java NIO.1 vs NIO.2
NIO.1 NIO.2
Selector AsynchronousChannelGroup
ServerSocketChannel AsynchronousServerSocketChannel
SocketChannel AsynchronousSocketChannel
SelectionKey CompletionHandler
Java.NIO.2 — Reading
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// prepare to read
readBuffer.clear();
AsynchronousSocketChannel channel = getChannel2();
channel.read(readBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
// buffer is ready for read
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
Java.NIO.2 — Writing
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// prepare to put data
writeBuffer.clear();
// putting data
// ...............
// prepare to write
writeBuffer.flip();
AsynchronousSocketChannel channel = getChannel2();
channel.write(writeBuffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
// writing has been completed
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
Java.NIO — NIO.1 server design
ServerSocketChannel channel = ServerSocketChannel.open();
channel.bind(new InetSocketAddress("localhost", 2222));
channel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
if (selector.select() == 0) {
Thread.sleep(1);
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey selectionKey = keyIterator.next();
if (selectionKey.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (selectionKey.isConnectable()) {
// a connection was established with a remote.
} else if (selectionKey.isReadable()) {
// a channel is ready for reading
} else if (selectionKey.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
Java.NIO — NIO.2 server design
AsynchronousChannelGroup group =
AsynchronousChannelGroup.withThreadPool(newFixedThreadPool(10));
AsynchronousServerSocketChannel channel = open(group);
channel.bind(new InetSocketAddress("localhost", 2222));
channel.accept(null, toHandler((client, attach) -> {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
client.read(readBuffer, null, toHandler((result, attachment) -> {
// buffer is ready for read
}));
client.write(writeBuffer, null, toHandler((result, attachment) -> {
// writing has been completed
}));
}));
public class NetworkServer {
AsynchronousServerSocketChannel channel;
CompletionHandler<AsynchronousSocketChannel, Void> handler;
public NetworkServer(SocketAddress address) throws IOException {
AsynchronousChannelGroup group = withFixedThreadPool(10, Thread::new);
handler = toHandler((channel, attach) -> processAccept(channel));
channel = AsynchronousServerSocketChannel.open(group);
channel.bind(address);
channel.accept(null, toHandler((clientChannel, attach) -> processAccept(clientChannel)));
}
private void processAccept(AsynchronousSocketChannel clientChannel) {
NetworkClient networkClient = new NetworkClient(clientChannel, message ->
out.println("Server: received: " + message));
networkClient.write("Hello! I'm NIO.2 server!n");
channel.accept(null, handler);
}
public void stop() throws IOException {
channel.close();
}
}
Java NIO.2 — Basic implementation of server
public class NetworkClient {
AtomicBoolean isWriting = new AtomicBoolean();
Deque<String> toWrite = new ConcurrentLinkedDeque<>();
Consumer<String> readFunction;
CompletionHandler<Integer, ByteBuffer> readHandler = toHandler((byteCount, buffer) -> finishRead(byteCount));
CompletionHandler<Integer, ByteBuffer> writeHandler = toHandler((byteCount, buffer) -> finishWrite());
ByteBuffer rb = allocateDirect(1024);
ByteBuffer wb = allocateDirect(1024);
AsynchronousSocketChannel channel;
public NetworkClient(AsynchronousSocketChannel channel, Consumer<String> readFunction) {
this.channel = channel;
this.readFunction = readFunction;
readNext();
}
private void finishRead(Integer byteCount) {
if(byteCount.equals(-1)) return;
readFunction.accept(NUtils.read(rb));
readNext();
}
private void finishWrite() {
if (isWriting.compareAndSet(true, false)) writeNext();
}
public void write(String message) {
toWrite.add(message);
if(isWriting.compareAndSet(false, true)) writeNext();
}
private void writeNext() {
if(toWrite.isEmpty()) return;
NUtils.write(wb, toWrite);
channel.write(wb, wb, writeHandler);
}
private void readNext() {
channel.read(rb, rb, readHandler);
}
}
Java NIO.2 — Basic implementation of server
new Thread(run(() -> {
final NetworkServer server = new NetworkServer(new InetSocketAddress(3333));
ConcurrentUtils.wait(counter);
server.stop();
})).start();
ThreadUtils.sleep(1000);
for (int i = 0, length = CLIENT_COUNT; i < length; i++) {
new Thread(run(() -> {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(3333));
writeLine(socket, "Hello! I'm client " + currentThread().getName());
System.out.println("Client: received: " + readLine(socket));
synchronized (counter) {
if (counter.decrementAndGet() == 0) {
ConcurrentUtils.notifyAll(counter);
} else {
ConcurrentUtils.wait(counter);
}
}
socket.close();
})).start();
}
Java NIO.2 — Test
Java NIO.2 — Test
Server: received: Hello! I'm client Thread-16
Server: received: Hello! I'm client Thread-19
Server: received: Hello! I'm client Thread-11
Server: received: Hello! I'm client Thread-20
Server: received: Hello! I'm client Thread-15
Server: received: Hello! I'm client Thread-18
Server: received: Hello! I'm client Thread-12
Server: received: Hello! I'm client Thread-14
Server: received: Hello! I'm client Thread-13
Server: received: Hello! I'm client Thread-17
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
Client: received: Hello! I'm NIO.2 server!
All thanks
Repository with my code examples:
https://bitbucket.org/JavaSabr/publictest

More Related Content

What's hot

Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Roman Elizarov
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Michal Balinski
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Roman Elizarov
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingJosé Paumard
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
Netty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityNetty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityC4Media
 
Being Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorMax Huang
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationSeven Peaks Speaks
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 

What's hot (20)

Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Practical non blocking microservices in java 8
Practical non blocking microservices in java 8Practical non blocking microservices in java 8
Practical non blocking microservices in java 8
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Netty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityNetty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/Connectivity
 
Being Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring Reactor
 
Gradle
GradleGradle
Gradle
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 
JDBC
JDBCJDBC
JDBC
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
spring-boot-fr.pdf
spring-boot-fr.pdfspring-boot-fr.pdf
spring-boot-fr.pdf
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Log4 J
Log4 JLog4 J
Log4 J
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Apache Maven 3
Apache Maven 3Apache Maven 3
Apache Maven 3
 

Viewers also liked

Viewers also liked (13)

Java Nio 2
Java Nio 2Java Nio 2
Java Nio 2
 
JAVA NIO
JAVA NIOJAVA NIO
JAVA NIO
 
Netty
NettyNetty
Netty
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 
Nio2
Nio2Nio2
Nio2
 
IBM InterConnect: Java vs JavaScript for Enterprise WebApps
IBM InterConnect: Java vs JavaScript for Enterprise WebAppsIBM InterConnect: Java vs JavaScript for Enterprise WebApps
IBM InterConnect: Java vs JavaScript for Enterprise WebApps
 
Event loop
Event loopEvent loop
Event loop
 
java.io - fluxos (streams) e arquivos
java.io - fluxos (streams) e arquivosjava.io - fluxos (streams) e arquivos
java.io - fluxos (streams) e arquivos
 
Java: Manipulação de Arquivos
Java:  Manipulação  de ArquivosJava:  Manipulação  de Arquivos
Java: Manipulação de Arquivos
 
Ficheiros em JAVA
Ficheiros em JAVAFicheiros em JAVA
Ficheiros em JAVA
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Apostila 8 sistema de arquivos
Apostila 8   sistema de arquivosApostila 8   sistema de arquivos
Apostila 8 sistema de arquivos
 

Similar to Java NIO.2

Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eveguest91855c
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Evel xf
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamImre Nagi
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
DCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystem
DCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystemDCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystem
DCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystemrudndccn
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 

Similar to Java NIO.2 (20)

Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
 
Embedded networks
Embedded networksEmbedded networks
Embedded networks
 
Sockets
SocketsSockets
Sockets
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Lecture10
Lecture10Lecture10
Lecture10
 
Java sockets
Java socketsJava sockets
Java sockets
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
分散式系統
分散式系統分散式系統
分散式系統
 
Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
 
DCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystem
DCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystemDCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystem
DCCN 2016 - Tutorial 2 - 4G for SmartGrid ecosystem
 
rtnetlink
rtnetlinkrtnetlink
rtnetlink
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 

More from *instinctools

ERP Customization for TV Services & Media Company
ERP Customization for TV Services & Media CompanyERP Customization for TV Services & Media Company
ERP Customization for TV Services & Media Company*instinctools
 
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdfIntegration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf*instinctools
 
Examples of custom intuitive dashboards in Odoo.pdf
Examples of custom intuitive dashboards in Odoo.pdfExamples of custom intuitive dashboards in Odoo.pdf
Examples of custom intuitive dashboards in Odoo.pdf*instinctools
 
CRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANYCRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANY*instinctools
 
BI Technologies and ECM-System For A Multi-Industry Corporation
BI Technologies and ECM-System For A Multi-Industry CorporationBI Technologies and ECM-System For A Multi-Industry Corporation
BI Technologies and ECM-System For A Multi-Industry Corporation*instinctools
 
How to protect sensitive data
How to protect sensitive dataHow to protect sensitive data
How to protect sensitive data*instinctools
 
Video streaming trends & technologies
Video streaming trends & technologiesVideo streaming trends & technologies
Video streaming trends & technologies*instinctools
 
Happy Programmer's day | 2021 | *instinctools in numbers
Happy Programmer's day | 2021 | *instinctools in numbersHappy Programmer's day | 2021 | *instinctools in numbers
Happy Programmer's day | 2021 | *instinctools in numbers*instinctools
 
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...*instinctools
 
Top software development trends of 2021
Top software development trends of 2021Top software development trends of 2021
Top software development trends of 2021*instinctools
 
6 hidden costs of cloud migration
6 hidden costs of cloud migration6 hidden costs of cloud migration
6 hidden costs of cloud migration*instinctools
 
Learning management system
Learning management systemLearning management system
Learning management system*instinctools
 
P2P trading platform - Blockchain solution for electricity provider
P2P trading platform - Blockchain solution for electricity providerP2P trading platform - Blockchain solution for electricity provider
P2P trading platform - Blockchain solution for electricity provider*instinctools
 
Business Analysis in IT
Business Analysis in ITBusiness Analysis in IT
Business Analysis in IT*instinctools
 
Electron. Build cross platform desktop apps with web technologies!
Electron. Build cross platform desktop apps with web technologies!Electron. Build cross platform desktop apps with web technologies!
Electron. Build cross platform desktop apps with web technologies!*instinctools
 
Videostream compression in iOS
Videostream compression in iOSVideostream compression in iOS
Videostream compression in iOS*instinctools
 
Apple Watch (Part 2)
Apple Watch (Part 2)Apple Watch (Part 2)
Apple Watch (Part 2)*instinctools
 
Apple Watch (Part 1)
Apple Watch (Part 1)Apple Watch (Part 1)
Apple Watch (Part 1)*instinctools
 

More from *instinctools (20)

ERP Customization for TV Services & Media Company
ERP Customization for TV Services & Media CompanyERP Customization for TV Services & Media Company
ERP Customization for TV Services & Media Company
 
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdfIntegration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
Integration Of Data Visualization Tools In Odoo: Pros And Cons.pdf
 
Examples of custom intuitive dashboards in Odoo.pdf
Examples of custom intuitive dashboards in Odoo.pdfExamples of custom intuitive dashboards in Odoo.pdf
Examples of custom intuitive dashboards in Odoo.pdf
 
CRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANYCRM FOR MARKETING COMPANY
CRM FOR MARKETING COMPANY
 
BI Technologies and ECM-System For A Multi-Industry Corporation
BI Technologies and ECM-System For A Multi-Industry CorporationBI Technologies and ECM-System For A Multi-Industry Corporation
BI Technologies and ECM-System For A Multi-Industry Corporation
 
How to protect sensitive data
How to protect sensitive dataHow to protect sensitive data
How to protect sensitive data
 
Video streaming trends & technologies
Video streaming trends & technologiesVideo streaming trends & technologies
Video streaming trends & technologies
 
Happy Programmer's day | 2021 | *instinctools in numbers
Happy Programmer's day | 2021 | *instinctools in numbersHappy Programmer's day | 2021 | *instinctools in numbers
Happy Programmer's day | 2021 | *instinctools in numbers
 
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
Data Integration: Huntflow and PowerBI | Case Study | Software Development Co...
 
Top software development trends of 2021
Top software development trends of 2021Top software development trends of 2021
Top software development trends of 2021
 
6 hidden costs of cloud migration
6 hidden costs of cloud migration6 hidden costs of cloud migration
6 hidden costs of cloud migration
 
Learning management system
Learning management systemLearning management system
Learning management system
 
P2P trading platform - Blockchain solution for electricity provider
P2P trading platform - Blockchain solution for electricity providerP2P trading platform - Blockchain solution for electricity provider
P2P trading platform - Blockchain solution for electricity provider
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Business Analysis in IT
Business Analysis in ITBusiness Analysis in IT
Business Analysis in IT
 
Electron. Build cross platform desktop apps with web technologies!
Electron. Build cross platform desktop apps with web technologies!Electron. Build cross platform desktop apps with web technologies!
Electron. Build cross platform desktop apps with web technologies!
 
Videostream compression in iOS
Videostream compression in iOSVideostream compression in iOS
Videostream compression in iOS
 
Apple Watch (Part 2)
Apple Watch (Part 2)Apple Watch (Part 2)
Apple Watch (Part 2)
 
Apple Watch (Part 1)
Apple Watch (Part 1)Apple Watch (Part 1)
Apple Watch (Part 1)
 
Viper architecture
Viper architectureViper architecture
Viper architecture
 

Recently uploaded

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

Java NIO.2

  • 2. Network socket Network socket is an endpoint of a connection across a computer network. Main types of Internet socket: ● Datagram sockets, which use User Datagram Protocol (UDP). ● Stream sockets, which use Transmission Control Protocol (TCP) or Stream Control Transmission Protocol (SCTP). ● Raw sockets, typically available in routers and other network equipment.
  • 3. Java IO vs NIO IO NIO Stream-oriented Buffer-oriented Blocking I/O Non-blocking I/O Selectors Channels
  • 4. Java.IO - Stream-oriented Data Source Program Data Destination Program 001001001111001001001001011 001001001111001001001001011
  • 5. Java.IO - Blocking I/O Socket Thread read data, block until ready read data, block until ready write data, block until ready write data, block until ready
  • 6. Java.IO — Work with data // read from socket Scanner sc = new Scanner(socket.getInputStream()); String string = sc.nextLine(); System.out.println("Received " + string); // write to socket PrintWriter pw = new PrintWriter(socket.getOutputStream()); pw.println("Hello");
  • 7. Java.NIO — Buffer-oriented & Non-blocking I/O Channel Buffer Thread read data into buffer fill data into buffer check data in buffer goto top
  • 8. Java.NIO — Work with data ByteBuffer readBuffer = ByteBuffer.allocate(1024); // prepare to read readBuffer.clear(); SocketChannel channel = getChannel(); channel.read(readBuffer); readBuffer.flip(); // reading the buffer // ...............… ByteBuffer writeBuffer = ByteBuffer.allocate(1024); // prepare to put data writeBuffer.clear(); // putting the data // ............... // prepare to write writeBuffer.flip(); channel.write(writeBuffer);
  • 9. Java.NIO — Selector & Channels Channel is a lightweight entity effeciently transporting data between sockets as a tube. Selector is a manager allowing a single thread to monitor multiple input channels.
  • 10. Java.IO - Classic IO server design Server Socket Thread Connection Thread Connection Thread Connection Thread Connection Thread
  • 11. Java.NIO — NIO server design Thread Selector Channel Channel Channel Channel
  • 12. Java.NIO — NIO server design ServerSocketChannel channel = ServerSocketChannel.open(); channel.bind(new InetSocketAddress("localhost", 2222)); channel.configureBlocking(false); Selector selector = Selector.open(); SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select() == 0) { Thread.sleep(1); continue; } Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey selectionKey = keyIterator.next(); if (selectionKey.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (selectionKey.isConnectable()) { // a connection was established with a remote. } else if (selectionKey.isReadable()) { // a channel is ready for reading } else if (selectionKey.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } }
  • 13. Java NIO.1 vs NIO.2 NIO.1 NIO.2 Selector AsynchronousChannelGroup ServerSocketChannel AsynchronousServerSocketChannel SocketChannel AsynchronousSocketChannel SelectionKey CompletionHandler
  • 14. Java.NIO.2 — Reading ByteBuffer readBuffer = ByteBuffer.allocate(1024); // prepare to read readBuffer.clear(); AsynchronousSocketChannel channel = getChannel2(); channel.read(readBuffer, null, new CompletionHandler<Integer, Object>() { @Override public void completed(Integer result, Object attachment) { // buffer is ready for read } @Override public void failed(Throwable exc, Object attachment) { exc.printStackTrace(); } });
  • 15. Java.NIO.2 — Writing ByteBuffer writeBuffer = ByteBuffer.allocate(1024); // prepare to put data writeBuffer.clear(); // putting data // ............... // prepare to write writeBuffer.flip(); AsynchronousSocketChannel channel = getChannel2(); channel.write(writeBuffer, null, new CompletionHandler<Integer, Object>() { @Override public void completed(Integer result, Object attachment) { // writing has been completed } @Override public void failed(Throwable exc, Object attachment) { exc.printStackTrace(); } });
  • 16. Java.NIO — NIO.1 server design ServerSocketChannel channel = ServerSocketChannel.open(); channel.bind(new InetSocketAddress("localhost", 2222)); channel.configureBlocking(false); Selector selector = Selector.open(); SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select() == 0) { Thread.sleep(1); continue; } Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey selectionKey = keyIterator.next(); if (selectionKey.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (selectionKey.isConnectable()) { // a connection was established with a remote. } else if (selectionKey.isReadable()) { // a channel is ready for reading } else if (selectionKey.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } }
  • 17. Java.NIO — NIO.2 server design AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(newFixedThreadPool(10)); AsynchronousServerSocketChannel channel = open(group); channel.bind(new InetSocketAddress("localhost", 2222)); channel.accept(null, toHandler((client, attach) -> { ByteBuffer readBuffer = ByteBuffer.allocate(1024); ByteBuffer writeBuffer = ByteBuffer.allocate(1024); client.read(readBuffer, null, toHandler((result, attachment) -> { // buffer is ready for read })); client.write(writeBuffer, null, toHandler((result, attachment) -> { // writing has been completed })); }));
  • 18. public class NetworkServer { AsynchronousServerSocketChannel channel; CompletionHandler<AsynchronousSocketChannel, Void> handler; public NetworkServer(SocketAddress address) throws IOException { AsynchronousChannelGroup group = withFixedThreadPool(10, Thread::new); handler = toHandler((channel, attach) -> processAccept(channel)); channel = AsynchronousServerSocketChannel.open(group); channel.bind(address); channel.accept(null, toHandler((clientChannel, attach) -> processAccept(clientChannel))); } private void processAccept(AsynchronousSocketChannel clientChannel) { NetworkClient networkClient = new NetworkClient(clientChannel, message -> out.println("Server: received: " + message)); networkClient.write("Hello! I'm NIO.2 server!n"); channel.accept(null, handler); } public void stop() throws IOException { channel.close(); } } Java NIO.2 — Basic implementation of server
  • 19. public class NetworkClient { AtomicBoolean isWriting = new AtomicBoolean(); Deque<String> toWrite = new ConcurrentLinkedDeque<>(); Consumer<String> readFunction; CompletionHandler<Integer, ByteBuffer> readHandler = toHandler((byteCount, buffer) -> finishRead(byteCount)); CompletionHandler<Integer, ByteBuffer> writeHandler = toHandler((byteCount, buffer) -> finishWrite()); ByteBuffer rb = allocateDirect(1024); ByteBuffer wb = allocateDirect(1024); AsynchronousSocketChannel channel; public NetworkClient(AsynchronousSocketChannel channel, Consumer<String> readFunction) { this.channel = channel; this.readFunction = readFunction; readNext(); } private void finishRead(Integer byteCount) { if(byteCount.equals(-1)) return; readFunction.accept(NUtils.read(rb)); readNext(); } private void finishWrite() { if (isWriting.compareAndSet(true, false)) writeNext(); } public void write(String message) { toWrite.add(message); if(isWriting.compareAndSet(false, true)) writeNext(); } private void writeNext() { if(toWrite.isEmpty()) return; NUtils.write(wb, toWrite); channel.write(wb, wb, writeHandler); } private void readNext() { channel.read(rb, rb, readHandler); } } Java NIO.2 — Basic implementation of server
  • 20. new Thread(run(() -> { final NetworkServer server = new NetworkServer(new InetSocketAddress(3333)); ConcurrentUtils.wait(counter); server.stop(); })).start(); ThreadUtils.sleep(1000); for (int i = 0, length = CLIENT_COUNT; i < length; i++) { new Thread(run(() -> { Socket socket = new Socket(); socket.connect(new InetSocketAddress(3333)); writeLine(socket, "Hello! I'm client " + currentThread().getName()); System.out.println("Client: received: " + readLine(socket)); synchronized (counter) { if (counter.decrementAndGet() == 0) { ConcurrentUtils.notifyAll(counter); } else { ConcurrentUtils.wait(counter); } } socket.close(); })).start(); } Java NIO.2 — Test
  • 21. Java NIO.2 — Test Server: received: Hello! I'm client Thread-16 Server: received: Hello! I'm client Thread-19 Server: received: Hello! I'm client Thread-11 Server: received: Hello! I'm client Thread-20 Server: received: Hello! I'm client Thread-15 Server: received: Hello! I'm client Thread-18 Server: received: Hello! I'm client Thread-12 Server: received: Hello! I'm client Thread-14 Server: received: Hello! I'm client Thread-13 Server: received: Hello! I'm client Thread-17 Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server!
  • 22. All thanks Repository with my code examples: https://bitbucket.org/JavaSabr/publictest