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

Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and TomorrowVMware Tanzu
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Toshiaki Maki
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeSimone Bordet
 
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
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in javaJayasankarPR2
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)WebStackAcademy
 
Reactive Programming In Java Using: Project Reactor
Reactive Programming In Java Using: Project ReactorReactive Programming In Java Using: Project Reactor
Reactive Programming In Java Using: Project ReactorKnoldus Inc.
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKirill Rozov
 

What's hot (20)

Project Reactor Now and Tomorrow
Project Reactor Now and TomorrowProject Reactor Now and Tomorrow
Project Reactor Now and Tomorrow
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Struts framework
Struts frameworkStruts framework
Struts framework
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1Introduction to Spring WebFlux #jsug #sf_a1
Introduction to Spring WebFlux #jsug #sf_a1
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
 
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
 
Lazy java
Lazy javaLazy java
Lazy java
 
Java IO
Java IOJava IO
Java IO
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
Reactive Programming In Java Using: Project Reactor
Reactive Programming In Java Using: Project ReactorReactive Programming In Java Using: Project Reactor
Reactive Programming In Java Using: Project Reactor
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 

Viewers also liked

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
 

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 ) (20)

NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
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
 

Recently uploaded

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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 AidPhilip Schwarz
 
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..pdfPearlKirahMaeRagusta1
 
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
 
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) SolutionOnePlan Solutions
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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 TechniquesVictorSzoltysek
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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
 
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
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
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 ...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

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.