SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Handling I/O in Java
 Techniques , Gotchas & Best Practices

                Hiranya Jayathilaka
           Senior Technical Lead – WSO2
                Apache Committer
Overview & Techniques
What is I/O?


Communication between the computer
       and the outside world
What’s in the Outside World?
• Human users
• Hardware devices
  – Monitors, keyboards, disk drives …
• Other computers and programs
Why Should We Care?
• An essential part of most programs
• Computers spend a lot of time performing
  nothing but I/O operations
• Very complicated business to deal with
• Ranks No.1 in the performance killer list
What are the Different Types of I/O?
•   Console I/O
•   Keyboard I/O
•   File I/O
•   Network I/O
•   …and possibly more
How Does Java Support I/O?
• The Java I/O API
  – The java.io package
  – Since JDK 1.0
  – Extensible
Stream




http://natureadore.blogspot.com/p/stream.html
Reading and Writing with Streams
  InputStream in = openInputStream();
  int b = in.read();

  byte[] data = new byte[1024];
  int len = in.read(data);

  OutputStream out = openOutputStream();
  out.write(b);
  Out.write(data, 0, len);
Readers and Writers
• Utilities for reading and writing character streams

  Reader reader = getReader();
  int ch = reader.read();

  char[] data = new char[1024];
  int len = reader.read(data);

  Writer writer = getWriter();
  writer.write(ch);
  writer.write(data, 0, len);
Bridging the Gap Between Bytes and
              Characters

InputStream in = openInputStream();
Reader reader = new InputStreamReader(in, “UTF-8”);

OutputStream out = openOutputStream();
Writer writer = new OutputStreamWriter(out, “UTF-8”);
Reading and Writing Typed Data
• Utilities to read primitive data and strings

DataInputStream in = new
  DataInputStream(openInputStream());
float num = in.readFloat();

DataOutputStream out = new
  DataOutputStream(openOutputStream());
out.writeFloat(num);
Buffered Vs Unbuffered
• Unbuffered – Each I/O request to the stream is
  directly handled by the underlying OS.
• Buffered – Each I/O request to the stream is
  executed on an in-memory buffer. OS invoked
  only when the buffer is empty.
Buffered I/O
InputStream in = new
  BufferedInputStream(openInputStream());
OutputStream out = new
  BufferedOutputStream(openOutputStream());

BufferedReader reader = new
  BufferedReader(getReader());
BufferedWriter writer = new
  BufferedWriter(getWriter());
Problems with Streams
    • Old school
    • Slow
    • Blocking




http://www.flickriver.com/photos/shazral/3565328977/
Alternatives?
• The Java New I/O (NIO) API
  – The java.nio package
  – Introduced in JDK 1.4
  – Leverages most efficient I/O operations of the
    underlying OS
  – Support for multiplexed, non-blocking I/O
Buffers
• A contiguous block of memory used to read
  and write bytes
• Memory can be allocated in a manner so that
  the underlying OS can directly access it (Direct
  buffers)
Reading and Writing with Buffers
 byte[] src = getData();
 ByteBuffer buf =
   ByteBuffer.allocateDirect(1024);
 buf.put(src);

 byte[] dest = new byte[1024];
 buf.flip();
 buf.get(dest);
Channels
• Represents an open connection to an I/O
  device
• Facilitates efficient bulk data transfers
  between devices and buffers
• A channel instance can be obtained from a
  class of the standard I/O package
Reading from a Channel
FileInputStream fin = new
  FileInputStream(“config.xml”);
FileChannel channel = fin.getChannel();
ByteBuffer buffer =
  ByteBuffer.allocateDirect(1024);
while (true) {
  buffer.clear();
  int len = channel.read(buffer);
  if (len == -1) {
      break;
  }
  buffer.flip();
  ...
}
Direct Channel Transfers
FileChannel in = new
  FileInputStream(source).getChannel();
FileChannel out = new
  FileOutputStream(target).getChannel();
in.transferTo(0, in.size(), out);
Memory Mapped Files
FileInputStream input = new
  FileInputStream(filename);
FileChannel channel = input.getChannel();
int fileLength = (int)channel.size();
MappedByteBuffer buffer =
  channel.map(FileChannel.MapMode.READ_ONLY,
  0, fileLength);
Multiplexed I/O with Selectors
    • A mechanism to register for I/O events on
      multiple channels and wait until at least one
      event occurs




http://tutorials.jenkov.com/java-nio/selectors.html
Registering for I/O Events
Selector selector = Selector.open();
channel1.register(selector, SelectionKey.OP_
  CONNECT | SelectionKey.OP_READ);
channel2.register(selector, SelectionKey.OP_
  CONNECT);
channel3.register(selector, SelectionKey.OP_
  WRITE);
‘Selecting’ a Channel
while (selector.select(500) > 0) {
  Set readyKeys = selector.selectedKeys();
  …
}
Non-blocking I/O
• Channels generally block until the I/O
  operations are complete (similar to streams)
• But some channel implementations can be
  made to work in a non-blocking manner

SocketChannel ch = SocketChannel.open();
ch.configureBlocking(false);
Standard I/O Vs. NIO
• A small demonstration…
NIO 2.0
• Introduced in JDK 1.7
• Even better support for file manipulation
  – Path, FileAttribute
  – Tree walk, File watch
• Asynchronous I/O
Hiranya’s Laws for Proper I/O
          Handling
  By a Developer for the Developers
Clean up your mess
Always close your streams and channels when you are done with
                            them
Buffering can be both your friend and
                enemy
  Don’t blindly wrap all streams with their buffered counter parts.
Buffering can yield good performance if you’re doing a lot of small I/O
   operations. Otherwise it only contributes to increased memory
                             consumption.
Don’t forget to flush after you!
If you’re using any buffered streams, make sure to flush them out
before closing the streams. Failing to do so may result in data loss.
There’s no escape from Karma and
                IOException
Developers often tend to ignore certain I/O exceptions thinking that they
 will never be thrown. But be aware that all I/O operations are prone to
             errors and may throw an exception at any time.
Java is platform independent – I/O is not
You need to do some additional work to make your I/O handling code
truly platform independent. Use the java.io.File abstraction instead of
strings to deal with files. Don’t make any assumptions about how the
             underlying OS handles certain I/O operations.
Concurrency and I/O Don’t Go Together
In a multi-user or multi-threaded environment, make sure that individual
 I/O operations are properly isolated. Attempting to access the same file
        or channel with concurrent threads can lead to disasters.
Nothing is perfect – Not even NIO
NIO is generally faster, but might not yield a significant performance gain
  in some scenarios. NIO code has a tendency to become complex and
difficult to understand. Also note that NIO is still an evolving technology.
Best way to write good I/O code is to not
              write them
  Use existing utilities and libraries that specialize in I/O handling.
Apache Commons IO
• A quick peek at the API and a demo
Questions?
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarAnimesh Sarkar
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 

Was ist angesagt? (20)

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Exception handling
Exception handlingException handling
Exception handling
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java IO
Java IOJava IO
Java IO
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Files in java
Files in javaFiles in java
Files in java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java package
Java packageJava package
Java package
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 

Ähnlich wie Handling I/O in Java

CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxSadhilAggarwal
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O YourHelper1
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)Elvin Gentiles
 
cpp-2013 #5 File and network input/output
cpp-2013 #5 File and network input/outputcpp-2013 #5 File and network input/output
cpp-2013 #5 File and network input/outputAmazon Web Services
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMohammed Rafi
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python ProgrammingAkhil Kaushik
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdprat0ham
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyMike Hagedorn
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangLyon Yang
 

Ähnlich wie Handling I/O in Java (20)

CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
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
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
NIO.pdf
NIO.pdfNIO.pdf
NIO.pdf
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
JAVA INTRODUCTION - 1
JAVA INTRODUCTION - 1JAVA INTRODUCTION - 1
JAVA INTRODUCTION - 1
 
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
Smash the Stack: Writing a Buffer Overflow Exploit (Win32)
 
cpp-2013 #5 File and network input/output
cpp-2013 #5 File and network input/outputcpp-2013 #5 File and network input/output
cpp-2013 #5 File and network input/output
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
 
Os lectures
Os lecturesOs lectures
Os lectures
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using Ruby
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
 
Introduction to Apache Beam
Introduction to Apache BeamIntroduction to Apache Beam
Introduction to Apache Beam
 

Mehr von Hiranya Jayathilaka

REST Coder: Auto Generating Client Stubs and Documentation for REST APIs
REST Coder: Auto Generating Client Stubs and Documentation for REST APIsREST Coder: Auto Generating Client Stubs and Documentation for REST APIs
REST Coder: Auto Generating Client Stubs and Documentation for REST APIsHiranya Jayathilaka
 
API Facade Pattern with Apache Synapse
API Facade Pattern with Apache SynapseAPI Facade Pattern with Apache Synapse
API Facade Pattern with Apache SynapseHiranya Jayathilaka
 
JAVA Colombo - What We've Been Up To
JAVA Colombo - What We've Been Up ToJAVA Colombo - What We've Been Up To
JAVA Colombo - What We've Been Up ToHiranya Jayathilaka
 

Mehr von Hiranya Jayathilaka (6)

REST Coder: Auto Generating Client Stubs and Documentation for REST APIs
REST Coder: Auto Generating Client Stubs and Documentation for REST APIsREST Coder: Auto Generating Client Stubs and Documentation for REST APIs
REST Coder: Auto Generating Client Stubs and Documentation for REST APIs
 
Apache JClouds
Apache JCloudsApache JClouds
Apache JClouds
 
API Facade Pattern with Apache Synapse
API Facade Pattern with Apache SynapseAPI Facade Pattern with Apache Synapse
API Facade Pattern with Apache Synapse
 
JAVA Colombo - What We've Been Up To
JAVA Colombo - What We've Been Up ToJAVA Colombo - What We've Been Up To
JAVA Colombo - What We've Been Up To
 
Welcome to JAVA Colombo
Welcome to JAVA ColomboWelcome to JAVA Colombo
Welcome to JAVA Colombo
 
Introduction to Apache Synapse
Introduction to Apache SynapseIntroduction to Apache Synapse
Introduction to Apache Synapse
 

Kürzlich hochgeladen

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Kürzlich hochgeladen (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Handling I/O in Java

  • 1. Handling I/O in Java Techniques , Gotchas & Best Practices Hiranya Jayathilaka Senior Technical Lead – WSO2 Apache Committer
  • 3. What is I/O? Communication between the computer and the outside world
  • 4. What’s in the Outside World? • Human users • Hardware devices – Monitors, keyboards, disk drives … • Other computers and programs
  • 5. Why Should We Care? • An essential part of most programs • Computers spend a lot of time performing nothing but I/O operations • Very complicated business to deal with • Ranks No.1 in the performance killer list
  • 6. What are the Different Types of I/O? • Console I/O • Keyboard I/O • File I/O • Network I/O • …and possibly more
  • 7. How Does Java Support I/O? • The Java I/O API – The java.io package – Since JDK 1.0 – Extensible
  • 9. Reading and Writing with Streams InputStream in = openInputStream(); int b = in.read(); byte[] data = new byte[1024]; int len = in.read(data); OutputStream out = openOutputStream(); out.write(b); Out.write(data, 0, len);
  • 10. Readers and Writers • Utilities for reading and writing character streams Reader reader = getReader(); int ch = reader.read(); char[] data = new char[1024]; int len = reader.read(data); Writer writer = getWriter(); writer.write(ch); writer.write(data, 0, len);
  • 11. Bridging the Gap Between Bytes and Characters InputStream in = openInputStream(); Reader reader = new InputStreamReader(in, “UTF-8”); OutputStream out = openOutputStream(); Writer writer = new OutputStreamWriter(out, “UTF-8”);
  • 12. Reading and Writing Typed Data • Utilities to read primitive data and strings DataInputStream in = new DataInputStream(openInputStream()); float num = in.readFloat(); DataOutputStream out = new DataOutputStream(openOutputStream()); out.writeFloat(num);
  • 13. Buffered Vs Unbuffered • Unbuffered – Each I/O request to the stream is directly handled by the underlying OS. • Buffered – Each I/O request to the stream is executed on an in-memory buffer. OS invoked only when the buffer is empty.
  • 14. Buffered I/O InputStream in = new BufferedInputStream(openInputStream()); OutputStream out = new BufferedOutputStream(openOutputStream()); BufferedReader reader = new BufferedReader(getReader()); BufferedWriter writer = new BufferedWriter(getWriter());
  • 15. Problems with Streams • Old school • Slow • Blocking http://www.flickriver.com/photos/shazral/3565328977/
  • 16. Alternatives? • The Java New I/O (NIO) API – The java.nio package – Introduced in JDK 1.4 – Leverages most efficient I/O operations of the underlying OS – Support for multiplexed, non-blocking I/O
  • 17. Buffers • A contiguous block of memory used to read and write bytes • Memory can be allocated in a manner so that the underlying OS can directly access it (Direct buffers)
  • 18. Reading and Writing with Buffers byte[] src = getData(); ByteBuffer buf = ByteBuffer.allocateDirect(1024); buf.put(src); byte[] dest = new byte[1024]; buf.flip(); buf.get(dest);
  • 19. Channels • Represents an open connection to an I/O device • Facilitates efficient bulk data transfers between devices and buffers • A channel instance can be obtained from a class of the standard I/O package
  • 20. Reading from a Channel FileInputStream fin = new FileInputStream(“config.xml”); FileChannel channel = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); while (true) { buffer.clear(); int len = channel.read(buffer); if (len == -1) { break; } buffer.flip(); ... }
  • 21. Direct Channel Transfers FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out);
  • 22. Memory Mapped Files FileInputStream input = new FileInputStream(filename); FileChannel channel = input.getChannel(); int fileLength = (int)channel.size(); MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);
  • 23. Multiplexed I/O with Selectors • A mechanism to register for I/O events on multiple channels and wait until at least one event occurs http://tutorials.jenkov.com/java-nio/selectors.html
  • 24. Registering for I/O Events Selector selector = Selector.open(); channel1.register(selector, SelectionKey.OP_ CONNECT | SelectionKey.OP_READ); channel2.register(selector, SelectionKey.OP_ CONNECT); channel3.register(selector, SelectionKey.OP_ WRITE);
  • 25. ‘Selecting’ a Channel while (selector.select(500) > 0) { Set readyKeys = selector.selectedKeys(); … }
  • 26. Non-blocking I/O • Channels generally block until the I/O operations are complete (similar to streams) • But some channel implementations can be made to work in a non-blocking manner SocketChannel ch = SocketChannel.open(); ch.configureBlocking(false);
  • 27. Standard I/O Vs. NIO • A small demonstration…
  • 28. NIO 2.0 • Introduced in JDK 1.7 • Even better support for file manipulation – Path, FileAttribute – Tree walk, File watch • Asynchronous I/O
  • 29. Hiranya’s Laws for Proper I/O Handling By a Developer for the Developers
  • 30. Clean up your mess Always close your streams and channels when you are done with them
  • 31. Buffering can be both your friend and enemy Don’t blindly wrap all streams with their buffered counter parts. Buffering can yield good performance if you’re doing a lot of small I/O operations. Otherwise it only contributes to increased memory consumption.
  • 32. Don’t forget to flush after you! If you’re using any buffered streams, make sure to flush them out before closing the streams. Failing to do so may result in data loss.
  • 33. There’s no escape from Karma and IOException Developers often tend to ignore certain I/O exceptions thinking that they will never be thrown. But be aware that all I/O operations are prone to errors and may throw an exception at any time.
  • 34. Java is platform independent – I/O is not You need to do some additional work to make your I/O handling code truly platform independent. Use the java.io.File abstraction instead of strings to deal with files. Don’t make any assumptions about how the underlying OS handles certain I/O operations.
  • 35. Concurrency and I/O Don’t Go Together In a multi-user or multi-threaded environment, make sure that individual I/O operations are properly isolated. Attempting to access the same file or channel with concurrent threads can lead to disasters.
  • 36. Nothing is perfect – Not even NIO NIO is generally faster, but might not yield a significant performance gain in some scenarios. NIO code has a tendency to become complex and difficult to understand. Also note that NIO is still an evolving technology.
  • 37. Best way to write good I/O code is to not write them Use existing utilities and libraries that specialize in I/O handling.
  • 38. Apache Commons IO • A quick peek at the API and a demo