SlideShare ist ein Scribd-Unternehmen logo
1 von 20
JAVA NIO ( New IO )
Import java.nio.*
Old IO Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws
IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
JAVA NIO Overview
Java NIO consist of the following core components:
Channels
Buffers
Selectors
Channels and Buffers
All IO in NIO starts with a Channel. A Channel is a bit like a stream. From the Channel, data can be
read into a Buffer. Data can also be written from a Buffer into a Channel.
Channel Types
Here is a list of the primary Channel implementations in Java NIO:
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel
As you can see, these channels cover UDP + TCP network IO, and file IO.
Buffers Types
Here is a list of the core Buffer implementations in Java NIO:
ByteBuffer
CharBuffer
DoubleBuffer
FloatBuffer
IntBuffer
LongBuffer
ShortBuffer
Buffer Layout
A Buffer has three properties you need to be familiar
with, in order to understand how a Buffer works.
These are:
capacity
position
limit
The meaning of position and limit depends on whether
the Buffer is in read or write mode. Capacity always
means the same, no matter the buffer mode.
Buffer Methods
● rewind()
● clear() and compact()
● mark() and reset()
Channel - Buffer Example
Using a Buffer to read and write data
typically follows this little 4-step process:
1. Write data into the Buffer
2. Call buffer.flip()
3. Read data out of the Buffer
4. Call buffer.clear() or buffer.compact()
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
//create buffer with capacity of 48 bytes
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf); //read into buffer.
while (bytesRead != -1) {
buf.flip(); //make buffer ready for read
while(buf.hasRemaining()){
System.out.print((char) buf.get()); // read 1 byte at a time
}
buf.clear(); //make buffer ready for writing
bytesRead = inChannel.read(buf);
}
aFile.close();
Selectors
A Selector allows a single thread to handle multiple Channels. This is handy if your application has many
connections (Channels) open, but only has low traffic on each connection. For instance, in a chat server.
● To use a Selector you register the Channel's with it.
Then you call it's select() method.
● This method will block until there is an event ready
for one of the registered channels.
● Once the method returns, the thread can then
process these events.
Examples of events are incoming connection, data received
etc.
Selectors
● Creating a Selector
Selector selector = Selector.open();
● Registering Channels with the Selector
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
1. The Channel must be in non-blocking mode to be used with a Selector.
2. This means that you cannot use FileChannel's with a Selector since FileChannel's cannot be switched
into non-blocking mode.
3. Socket channels will work fine though.
Selectors
● There is an "interest set", meaning what events you are interested in listening for in the Channel, via the Selector. There are four
different events you can listen for:
1. Connect
2. Accept
3. Read
4. Write
● These four events are represented by the four SelectionKey constants:
1. SelectionKey.OP_CONNECT
2. SelectionKey.OP_ACCEPT
3. SelectionKey.OP_READ
4. SelectionKey.OP_WRITE
● If you are interested in more than one event, OR the constants together, like this:
int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
SelectionKey key = channel.register(selector, interestSet);
This SelectionKey object contains
a few interesting properties:
The interest set
The ready set
The Channel
The Selector
An attached object (optional)
Select Methods
Here are the select() methods:
1. int select()
2. int select(long timeout)
3. int selectNow()
● select() blocks until at least one channel is ready for the events you registered for.
● select(long timeout) does the same as select() except it blocks for a maximum of timeoutmilliseconds (the
parameter).
● selectNow() doesn't block at all. It returns immediately with whatever channels are ready.
Selector Example
Selector selector = Selector.open();
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
// Or more no of channels
while(true) {
int readyChannels = selector.select();
if(readyChannels == 0) continue;
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
}
JAVA NIO Pipe
A Java NIO Pipe is a one-way data connection between two threads. A Pipe has a source channel and a sink channel.
You write data to the sink channel. This data can then be read from the source channel.
● Creating a Pipe
Pipe pipe = Pipe.open();
● Writing to a Pipe
To write to a Pipe you need to access the sink channel.
Pipe.SinkChannel sinkChannel = pipe.sink();
String newData = "New String to write to file...";
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
sinkChannel.write(buf);
}
● Reading from a Pipe
To read from a Pipe you need to access the
source channel
Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
Example : Pipe
Difference between IO and NIO
IO NIO
Stream Oriented Buffer Oriented
Blocking IO Non Blocking IO
Selectors
Summary
NIO allows you to manage multiple channels using only a single (or fewer) threads.
To manage thousands of open connections simultaneously, which each only send a little data, Ex. chat server,
implementing the server in NIO is probably an advantage.
Similarly, if we need to keep a lot of open connections to other computers, e.g. in a P2P network, using a single
thread to manage all of your outbound connections might be an advantage.
When we have fewer connections with very high bandwidth, sending a lot of data at a time, standard IO server
implementation is better.
References
http://tutorials.jenkov.com/java-nio
http://howtodoinjava.com/java-nio-tutorials/
Thank you :)

Weitere ähnliche Inhalte

Was ist angesagt?

servlet in java
servlet in javaservlet in java
servlet in javasowfi
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyVMware Tanzu
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootOmri Spector
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8José Paumard
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 

Was ist angesagt? (20)

servlet in java
servlet in javaservlet in java
servlet in java
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Spring boot
Spring bootSpring boot
Spring boot
 
Files in java
Files in javaFiles in java
Files in java
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
How to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor NettyHow to Avoid Common Mistakes When Using Reactor Netty
How to Avoid Common Mistakes When Using Reactor Netty
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 

Andere mochten auch

java.io - fluxos (streams) e arquivos
java.io - fluxos (streams) e arquivosjava.io - fluxos (streams) e arquivos
java.io - fluxos (streams) e arquivosMarcello Thiry
 
Java: Manipulação de Arquivos
Java:  Manipulação  de ArquivosJava:  Manipulação  de Arquivos
Java: Manipulação de ArquivosArthur Emanuel
 
Baobab / Boab Presentation. Marketing media. Export.
Baobab / Boab Presentation. Marketing media. Export.Baobab / Boab Presentation. Marketing media. Export.
Baobab / Boab Presentation. Marketing media. Export.Josef Perner.
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
Pompeii Archaeology and History
Pompeii Archaeology and History Pompeii Archaeology and History
Pompeii Archaeology and History Hasan Mohammad
 
Internship Final Report-ROBI.2014
Internship Final Report-ROBI.2014Internship Final Report-ROBI.2014
Internship Final Report-ROBI.2014Ehshan Ahmed
 
Apostila 8 sistema de arquivos
Apostila 8   sistema de arquivosApostila 8   sistema de arquivos
Apostila 8 sistema de arquivosPaulo Fonseca
 
International Trade Example
International Trade ExampleInternational Trade Example
International Trade ExampleOrmita Hong Kong
 
Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...
Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...
Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...Brussels Briefings (brusselsbriefings.net)
 
Phases of globalization(1)
Phases of globalization(1)Phases of globalization(1)
Phases of globalization(1)htulungenaram
 
International Trade
International TradeInternational Trade
International TradeEthel
 

Andere mochten auch (15)

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
 
Baobab / Boab Presentation. Marketing media. Export.
Baobab / Boab Presentation. Marketing media. Export.Baobab / Boab Presentation. Marketing media. Export.
Baobab / Boab Presentation. Marketing media. Export.
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Ficheiros em JAVA
Ficheiros em JAVAFicheiros em JAVA
Ficheiros em JAVA
 
Semantic
SemanticSemantic
Semantic
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Pompeii Archaeology and History
Pompeii Archaeology and History Pompeii Archaeology and History
Pompeii Archaeology and History
 
Internship Final Report-ROBI.2014
Internship Final Report-ROBI.2014Internship Final Report-ROBI.2014
Internship Final Report-ROBI.2014
 
Apostila 8 sistema de arquivos
Apostila 8   sistema de arquivosApostila 8   sistema de arquivos
Apostila 8 sistema de arquivos
 
International Trade Example
International Trade ExampleInternational Trade Example
International Trade Example
 
Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...
Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...
Brussels Briefing 44: Fredrick Masinde, Business Development Manager, Undugu ...
 
Phases of globalization(1)
Phases of globalization(1)Phases of globalization(1)
Phases of globalization(1)
 
International Trade
International TradeInternational Trade
International Trade
 
Quota Sampling
Quota SamplingQuota Sampling
Quota Sampling
 

Ähnlich wie Java nio ( new io ) (20)

NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
 
Nio nio2
Nio nio2Nio nio2
Nio nio2
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
Ipc in linux
Ipc in linuxIpc in linux
Ipc in linux
 
Ipc in linux
Ipc in linuxIpc in linux
Ipc in linux
 
Io Streams
Io StreamsIo Streams
Io Streams
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
Java sockets
Java socketsJava sockets
Java sockets
 
15. text files
15. text files15. text files
15. text files
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Io stream
Io streamIo stream
Io stream
 

Kürzlich hochgeladen

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 

Kürzlich hochgeladen (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 

Java nio ( new io )

  • 1. JAVA NIO ( New IO ) Import java.nio.*
  • 2. Old IO Example import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
  • 3. JAVA NIO Overview Java NIO consist of the following core components: Channels Buffers Selectors
  • 4. Channels and Buffers All IO in NIO starts with a Channel. A Channel is a bit like a stream. From the Channel, data can be read into a Buffer. Data can also be written from a Buffer into a Channel.
  • 5. Channel Types Here is a list of the primary Channel implementations in Java NIO: FileChannel DatagramChannel SocketChannel ServerSocketChannel As you can see, these channels cover UDP + TCP network IO, and file IO.
  • 6. Buffers Types Here is a list of the core Buffer implementations in Java NIO: ByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer
  • 7. Buffer Layout A Buffer has three properties you need to be familiar with, in order to understand how a Buffer works. These are: capacity position limit The meaning of position and limit depends on whether the Buffer is in read or write mode. Capacity always means the same, no matter the buffer mode.
  • 8. Buffer Methods ● rewind() ● clear() and compact() ● mark() and reset()
  • 9. Channel - Buffer Example Using a Buffer to read and write data typically follows this little 4-step process: 1. Write data into the Buffer 2. Call buffer.flip() 3. Read data out of the Buffer 4. Call buffer.clear() or buffer.compact() RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); //create buffer with capacity of 48 bytes ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); //read into buffer. while (bytesRead != -1) { buf.flip(); //make buffer ready for read while(buf.hasRemaining()){ System.out.print((char) buf.get()); // read 1 byte at a time } buf.clear(); //make buffer ready for writing bytesRead = inChannel.read(buf); } aFile.close();
  • 10. Selectors A Selector allows a single thread to handle multiple Channels. This is handy if your application has many connections (Channels) open, but only has low traffic on each connection. For instance, in a chat server. ● To use a Selector you register the Channel's with it. Then you call it's select() method. ● This method will block until there is an event ready for one of the registered channels. ● Once the method returns, the thread can then process these events. Examples of events are incoming connection, data received etc.
  • 11. Selectors ● Creating a Selector Selector selector = Selector.open(); ● Registering Channels with the Selector channel.configureBlocking(false); SelectionKey key = channel.register(selector, SelectionKey.OP_READ); 1. The Channel must be in non-blocking mode to be used with a Selector. 2. This means that you cannot use FileChannel's with a Selector since FileChannel's cannot be switched into non-blocking mode. 3. Socket channels will work fine though.
  • 12. Selectors ● There is an "interest set", meaning what events you are interested in listening for in the Channel, via the Selector. There are four different events you can listen for: 1. Connect 2. Accept 3. Read 4. Write ● These four events are represented by the four SelectionKey constants: 1. SelectionKey.OP_CONNECT 2. SelectionKey.OP_ACCEPT 3. SelectionKey.OP_READ 4. SelectionKey.OP_WRITE ● If you are interested in more than one event, OR the constants together, like this: int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE; SelectionKey key = channel.register(selector, interestSet); This SelectionKey object contains a few interesting properties: The interest set The ready set The Channel The Selector An attached object (optional)
  • 13. Select Methods Here are the select() methods: 1. int select() 2. int select(long timeout) 3. int selectNow() ● select() blocks until at least one channel is ready for the events you registered for. ● select(long timeout) does the same as select() except it blocks for a maximum of timeoutmilliseconds (the parameter). ● selectNow() doesn't block at all. It returns immediately with whatever channels are ready.
  • 14. Selector Example Selector selector = Selector.open(); channel.configureBlocking(false); SelectionKey key = channel.register(selector, SelectionKey.OP_READ); // Or more no of channels while(true) { int readyChannels = selector.select(); if(readyChannels == 0) continue; Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while(keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if(key.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (key.isConnectable()) { // a connection was established with a remote server. } else if (key.isReadable()) { // a channel is ready for reading } else if (key.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } }
  • 15. JAVA NIO Pipe A Java NIO Pipe is a one-way data connection between two threads. A Pipe has a source channel and a sink channel. You write data to the sink channel. This data can then be read from the source channel.
  • 16. ● Creating a Pipe Pipe pipe = Pipe.open(); ● Writing to a Pipe To write to a Pipe you need to access the sink channel. Pipe.SinkChannel sinkChannel = pipe.sink(); String newData = "New String to write to file..."; ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { sinkChannel.write(buf); } ● Reading from a Pipe To read from a Pipe you need to access the source channel Pipe.SourceChannel sourceChannel = pipe.source(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); Example : Pipe
  • 17. Difference between IO and NIO IO NIO Stream Oriented Buffer Oriented Blocking IO Non Blocking IO Selectors
  • 18. Summary NIO allows you to manage multiple channels using only a single (or fewer) threads. To manage thousands of open connections simultaneously, which each only send a little data, Ex. chat server, implementing the server in NIO is probably an advantage. Similarly, if we need to keep a lot of open connections to other computers, e.g. in a P2P network, using a single thread to manage all of your outbound connections might be an advantage. When we have fewer connections with very high bandwidth, sending a lot of data at a time, standard IO server implementation is better.