SlideShare a Scribd company logo
1 of 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 :)

More Related Content

What's hot

What's hot (20)

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
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Reactive programming intro
Reactive programming introReactive programming intro
Reactive programming intro
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java I/O
Java I/OJava I/O
Java I/O
 
[Webinar]: Working with Reactive Spring
[Webinar]: Working with Reactive Spring[Webinar]: Working with Reactive Spring
[Webinar]: Working with Reactive Spring
 
The top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scaleThe top 3 challenges running multi-tenant Flink at scale
The top 3 challenges running multi-tenant Flink at scale
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Viewers also liked

IO In Java
IO In JavaIO In Java
IO In Java
parag
 
Internship Final Report-ROBI.2014
Internship Final Report-ROBI.2014Internship Final Report-ROBI.2014
Internship Final Report-ROBI.2014
Ehshan Ahmed
 
International Trade Example
International Trade ExampleInternational Trade Example
International Trade Example
Ormita Hong Kong
 

Viewers also liked (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
 

Similar to Java nio ( new io )

Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
Teguh Nugraha
 
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
RathanMB
 

Similar to Java nio ( new io ) (20)

NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
 
Nio nio2
Nio nio2Nio nio2
Nio 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
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 

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.