SlideShare a Scribd company logo
1 of 14
NIO
Why NIO ?
Streams versus blocks
A stream-oriented I/O system deals with data
one byte at a time. An input stream produces
one byte of data, and an output stream
consumes one byte of data .
A block-oriented I/O system deals with data in
blocks

http://www.youtube.com/zarigatongy
Buffer Basics
• A buffer is an array of primitive data elements
wrapped inside an object.
• Attributes
– Capacity
– Limit
– Position
– Mark
0 <= mark <= position <= limit <= capacity
http://www.youtube.com/zarigatongy
Buffer Types
• ByteBuffer  Direct Buffer
• CharBuffer
• ShortBuffer
• IntBuffer
• LongBuffer
• FloatBuffer
• DoubleBuffer

http://www.youtube.com/zarigatongy
ByteBuffer Visual Representation
0

1

X

2

3

4

5

6

0

7

8

10

MARK POSITION

Limit

let's assume that our buffer has a total capacity of Ten bytes

http://www.youtube.com/zarigatongy

9

10

CAPACITY
Data in Buffer
buffer.put((byte)'H').put((byte)'e').put((byte)'l').
put((byte)'l').put((byte) ’o’)
0

1

2

h
48

e
65

l
6c

X
MARK

3
l
6c

4

5

6

7

8

9

0
6f

5

10

POSITION

Limit
http://www.youtube.com/zarigatongy

10

CAPACITY
Buffer Flipping
buffer.flip()
0

1

2

h
48

e
65

l
6c

X
MARK

3
l
6c

4

5

6

7

8

9

o
6f

0

6

POSITION

Limit
http://www.youtube.com/zarigatongy

10

CAPACITY
Buffer Draining
• hasRemaining( )
for (int i = 0; buffer.hasRemaining( ), i++) {
buffer.get( );
}
• remaining( )
int count = buffer.remaining( );
for (int i = 0; i < count, i++) {
buffer.get( );
}
http://www.youtube.com/zarigatongy
Buffer Marking
buffer.position(2).mark( ).position(4);
0

1

2

3

4

h
48

r
65

l
6c

l
6c

o
6f

2
MARK

5

6

4

7

6

POSITION

Limit

rewind( ), clear( ), and flip( ) always discard the mark
clear( ) method makes a buffer empty
reset( ) returns the position to a previously set mark

http://www.youtube.com/zarigatongy

8

9

10
CAPACITY
Buffer Comparison
• Two buffers are considered to be equal
– Both objects are the same type
– Both buffers have the same number of remaining elements
POSITION

LIMIT

h
68

e
65

l
6c

l
6c

t
74

i
69

l
6c

Buffer
1

l
6c

POSITION

o
6f

Buffer
2

LIMIT
EQUAL Buffer Demo
http://www.youtube.com/zarigatongy
Creating Buffer
• Allocation
– ByteBuffer buffer = ByteBuffer.allocate( 1024 );
– CharBuffer charBuffer = CharBuffer.allocate (100);

• Wrap
– byte array[] = new byte[1024]; ByteBuffer buffer =
ByteBuffer.wrap( array );
– char [] myArray = new char [100]; CharBuffer charbuffer =
CharBuffer.wrap (myArray);
– CharBuffer charbuffer = CharBuffer.wrap (myArray, 12, 90);

http://www.youtube.com/zarigatongy
Duplicating Buffer
• returns a new byte buffer that shares the old buffer's
content. Changes to the old buffer's content will be
visible in the new buffer, and vice versa.
• The new buffer's capacity, limit, position, and mark
values will be identical to those of this buffer. The new
buffer will be direct if, and only if, this buffer is
direct, and it will be read-only if, and only if, this buffer
is read-only
• CharBuffer buffer = CharBuffer.allocate (8);
buffer.position (3).limit (6).mark( ).position (5);
CharBuffer dupeBuffer = buffer.duplicate( );
http://www.youtube.com/zarigatongy
Buffer Slicing
• The slice() method creates a kind of sub-buffer from an
existing buffer
• The content of the new buffer will start at this buffer's
current position. Changes to this buffer's content will
be visible in the new buffer, and vice versa; the two
buffers' position, limit, and mark values will be
independent.
• The new buffer's position will be zero, its capacity and
its limit will be the number of bytes remaining in this
buffer, and its mark will be undefined. The new buffer
will be direct if, and only if, this buffer is direct, and it
will be read-only if, and only if, this buffer is read-only.
http://www.youtube.com/zarigatongy
Direct Buffers
• Direct Buffer– The ByteBuffer
– A direct buffer is one whose memory is allocated
in a special way to increase I/O speed
– Given a direct byte buffer, the Java virtual machine
will make a best effort to perform native I/O
operations directly upon it. That is, it will attempt
to avoid copying the buffer's content to (or from)
an intermediate buffer before (or after) each
invocation of one of the underlying operating
system's native I/O operations.
http://www.youtube.com/zarigatongy

More Related Content

Viewers also liked

Viewers also liked (15)

Saa s companies, are you segmenting your customer acquisition channels correc...
Saa s companies, are you segmenting your customer acquisition channels correc...Saa s companies, are you segmenting your customer acquisition channels correc...
Saa s companies, are you segmenting your customer acquisition channels correc...
 
Nio java
Nio javaNio java
Nio java
 
Project profilevol 1
Project profilevol 1Project profilevol 1
Project profilevol 1
 
Java nio
Java nioJava nio
Java nio
 
Nio trick and trap
Nio trick and trapNio trick and trap
Nio trick and trap
 
Java Nio 2
Java Nio 2Java Nio 2
Java Nio 2
 
Hesham Ramadan - CV - 2016
Hesham Ramadan - CV - 2016Hesham Ramadan - CV - 2016
Hesham Ramadan - CV - 2016
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
 
PPPoE: PPP over Ethernet
PPPoE: PPP over EthernetPPPoE: PPP over Ethernet
PPPoE: PPP over Ethernet
 
Eleritrocitoyelmetabolismodelhierro 130903122229-
Eleritrocitoyelmetabolismodelhierro 130903122229-Eleritrocitoyelmetabolismodelhierro 130903122229-
Eleritrocitoyelmetabolismodelhierro 130903122229-
 
La salle
La salleLa salle
La salle
 
Grupo 2
Grupo 2Grupo 2
Grupo 2
 
Dia del planeta Tierra
Dia del planeta TierraDia del planeta Tierra
Dia del planeta Tierra
 
Derivadas
DerivadasDerivadas
Derivadas
 
Presentacion
PresentacionPresentacion
Presentacion
 

Similar to Java NIO Buffer basics

Netty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and BuffersNetty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and BuffersRick Hightower
 
(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014
(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014
(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014Amazon Web Services
 
Ame 2280 mq for z os latest features
Ame 2280 mq for z os latest featuresAme 2280 mq for z os latest features
Ame 2280 mq for z os latest featuresPete Siddall
 
IBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep Dive
IBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep DiveIBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep Dive
IBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep DivePaul Dennis
 
Computer organization memory hierarchy
Computer organization memory hierarchyComputer organization memory hierarchy
Computer organization memory hierarchyAJAL A J
 
IBM Latest Features Deep Dive
IBM Latest Features Deep DiveIBM Latest Features Deep Dive
IBM Latest Features Deep DiveIBM Systems UKI
 
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...Michael Stack
 
bufferoverflow-151214121251 presentation
bufferoverflow-151214121251 presentationbufferoverflow-151214121251 presentation
bufferoverflow-151214121251 presentationJohnLagman3
 
Using Basho Bench to Load Test Distributed Applications
Using Basho Bench to Load Test Distributed ApplicationsUsing Basho Bench to Load Test Distributed Applications
Using Basho Bench to Load Test Distributed ApplicationsBasho Technologies
 
Java one2015 - Work With Hundreds of Hot Terabytes in JVMs
Java one2015 - Work With Hundreds of Hot Terabytes in JVMsJava one2015 - Work With Hundreds of Hot Terabytes in JVMs
Java one2015 - Work With Hundreds of Hot Terabytes in JVMsSpeedment, Inc.
 
SAP hybris Caching and Monitoring
SAP hybris Caching and MonitoringSAP hybris Caching and Monitoring
SAP hybris Caching and MonitoringZhuo Huang
 
HBase Blockcache 101
HBase Blockcache 101HBase Blockcache 101
HBase Blockcache 101Nick Dimiduk
 
Spring introduction
Spring introductionSpring introduction
Spring introductionLê Hảo
 

Similar to Java NIO Buffer basics (20)

Buffers (1)
Buffers (1)Buffers (1)
Buffers (1)
 
Netty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and BuffersNetty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and Buffers
 
(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014
(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014
(BDT307) Running NoSQL on Amazon EC2 | AWS re:Invent 2014
 
Ame 2280 mq for z os latest features
Ame 2280 mq for z os latest featuresAme 2280 mq for z os latest features
Ame 2280 mq for z os latest features
 
IBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep Dive
IBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep DiveIBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep Dive
IBM Impact 2014 AMC-1876: IBM WebSphere MQ for z/OS: Latest Features Deep Dive
 
Computer organization memory hierarchy
Computer organization memory hierarchyComputer organization memory hierarchy
Computer organization memory hierarchy
 
IBM Latest Features Deep Dive
IBM Latest Features Deep DiveIBM Latest Features Deep Dive
IBM Latest Features Deep Dive
 
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
hbaseconasia2019 Further GC optimization for HBase 2.x: Reading HFileBlock in...
 
Mapping
MappingMapping
Mapping
 
bufferoverflow-151214121251 presentation
bufferoverflow-151214121251 presentationbufferoverflow-151214121251 presentation
bufferoverflow-151214121251 presentation
 
Buffer overflow
Buffer overflowBuffer overflow
Buffer overflow
 
Nio nio2
Nio nio2Nio nio2
Nio nio2
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
cache memory
 cache memory cache memory
cache memory
 
Using Basho Bench to Load Test Distributed Applications
Using Basho Bench to Load Test Distributed ApplicationsUsing Basho Bench to Load Test Distributed Applications
Using Basho Bench to Load Test Distributed Applications
 
Java one2015 - Work With Hundreds of Hot Terabytes in JVMs
Java one2015 - Work With Hundreds of Hot Terabytes in JVMsJava one2015 - Work With Hundreds of Hot Terabytes in JVMs
Java one2015 - Work With Hundreds of Hot Terabytes in JVMs
 
SAP hybris Caching and Monitoring
SAP hybris Caching and MonitoringSAP hybris Caching and Monitoring
SAP hybris Caching and Monitoring
 
HBase Blockcache 101
HBase Blockcache 101HBase Blockcache 101
HBase Blockcache 101
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
The Future of Apache Storm
The Future of Apache StormThe Future of Apache Storm
The Future of Apache Storm
 

Recently uploaded

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Recently uploaded (20)

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

Java NIO Buffer basics

  • 2. Streams versus blocks A stream-oriented I/O system deals with data one byte at a time. An input stream produces one byte of data, and an output stream consumes one byte of data . A block-oriented I/O system deals with data in blocks http://www.youtube.com/zarigatongy
  • 3. Buffer Basics • A buffer is an array of primitive data elements wrapped inside an object. • Attributes – Capacity – Limit – Position – Mark 0 <= mark <= position <= limit <= capacity http://www.youtube.com/zarigatongy
  • 4. Buffer Types • ByteBuffer  Direct Buffer • CharBuffer • ShortBuffer • IntBuffer • LongBuffer • FloatBuffer • DoubleBuffer http://www.youtube.com/zarigatongy
  • 5. ByteBuffer Visual Representation 0 1 X 2 3 4 5 6 0 7 8 10 MARK POSITION Limit let's assume that our buffer has a total capacity of Ten bytes http://www.youtube.com/zarigatongy 9 10 CAPACITY
  • 6. Data in Buffer buffer.put((byte)'H').put((byte)'e').put((byte)'l'). put((byte)'l').put((byte) ’o’) 0 1 2 h 48 e 65 l 6c X MARK 3 l 6c 4 5 6 7 8 9 0 6f 5 10 POSITION Limit http://www.youtube.com/zarigatongy 10 CAPACITY
  • 8. Buffer Draining • hasRemaining( ) for (int i = 0; buffer.hasRemaining( ), i++) { buffer.get( ); } • remaining( ) int count = buffer.remaining( ); for (int i = 0; i < count, i++) { buffer.get( ); } http://www.youtube.com/zarigatongy
  • 9. Buffer Marking buffer.position(2).mark( ).position(4); 0 1 2 3 4 h 48 r 65 l 6c l 6c o 6f 2 MARK 5 6 4 7 6 POSITION Limit rewind( ), clear( ), and flip( ) always discard the mark clear( ) method makes a buffer empty reset( ) returns the position to a previously set mark http://www.youtube.com/zarigatongy 8 9 10 CAPACITY
  • 10. Buffer Comparison • Two buffers are considered to be equal – Both objects are the same type – Both buffers have the same number of remaining elements POSITION LIMIT h 68 e 65 l 6c l 6c t 74 i 69 l 6c Buffer 1 l 6c POSITION o 6f Buffer 2 LIMIT EQUAL Buffer Demo http://www.youtube.com/zarigatongy
  • 11. Creating Buffer • Allocation – ByteBuffer buffer = ByteBuffer.allocate( 1024 ); – CharBuffer charBuffer = CharBuffer.allocate (100); • Wrap – byte array[] = new byte[1024]; ByteBuffer buffer = ByteBuffer.wrap( array ); – char [] myArray = new char [100]; CharBuffer charbuffer = CharBuffer.wrap (myArray); – CharBuffer charbuffer = CharBuffer.wrap (myArray, 12, 90); http://www.youtube.com/zarigatongy
  • 12. Duplicating Buffer • returns a new byte buffer that shares the old buffer's content. Changes to the old buffer's content will be visible in the new buffer, and vice versa. • The new buffer's capacity, limit, position, and mark values will be identical to those of this buffer. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only • CharBuffer buffer = CharBuffer.allocate (8); buffer.position (3).limit (6).mark( ).position (5); CharBuffer dupeBuffer = buffer.duplicate( ); http://www.youtube.com/zarigatongy
  • 13. Buffer Slicing • The slice() method creates a kind of sub-buffer from an existing buffer • The content of the new buffer will start at this buffer's current position. Changes to this buffer's content will be visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values will be independent. • The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only. http://www.youtube.com/zarigatongy
  • 14. Direct Buffers • Direct Buffer– The ByteBuffer – A direct buffer is one whose memory is allocated in a special way to increase I/O speed – Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations. http://www.youtube.com/zarigatongy

Editor's Notes

  1. Hello and welcome to NIO, in this video we will cover the basics of buffer before that let’s focus why we need NIO. NIO was created to allow Java programmers to implement high-speed I/O without having to write custom native code. NIO moves the most time-consuming I/O activities (namely, filling and draining buffers) back into the operating system, thus allowing for a great increase in speed.
  2. Before moving to Buffer Basics recap the following concept like Stream IO vs Block IO. Java NIO and IO is that IO is stream oriented, where NIO is buffer oriented. So, what does that mean? Java IO&apos;s various streams are blocking. That means, that when a thread invokes a read() or write(), that thread is blocked until there is some data to read, or the data is fully written. The thread can do nothing else in the meantime. Java NIO&apos;s non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or nothing at all, if no data is currently available. Rather than remain blocked until data becomes available for reading, the thread can go on with something else
  3. What is a Buffer ?. A buffer is an array of primitive data elements wrapped inside an object. There are four attributes all buffer.CapacityThe capacity of a buffer specifies the maximum amount of data that can be stored therein. Limit The first element of the buffer that should not be read or written.PositionLikewise, when you are writing to a channel, you get the data from a buffer. The position value keeps track of how much you have gotten from the buffer. More precisely, it specifies from which array element the next byte will come Mark Calling mark( ) sets mark = position.
  4. Kinds of buffers The most commonly used kind of buffer is the ByteBuffer. Each of the Buffer classes is an instance of the Buffer interface. Types of Buffers are ByteBuffer also known as Direct Buffer, other fall in category of nondirect buffer like CharBuffer,ShortBuffer,IntBuffer,LongBuffer,FloatBuffer,DoubleBuffer
  5. Byte Buffer Visual Representation. Figure shows a logical view of a newly created ByteBuffer with a capacity of 10. The position is set to 0, the capacity and Limit are set to 10.Mark is undefined, capacity is fixed, position will change as buffer moves.
  6. In this example we Just fill the byte buffer with byte values representing the ASCII character sequence Hello into a ByteBuffer object named buffer. As we can see that MARK remains undefined the Limit and capacity remains unchanged the POSITION only moves, every PUT of byte value increment the position by one, Now the question is what trigger the LIMIT and MARK attribute to change, we will get to know when we see the buffer flipping.
  7. What is buffer flipping,when are ready to write our data to an output channel. Before we can do this, we must call the flip() method. This method does two crucial things: It sets the limit to the current position. It sets the position to 0. Why we need to perform flip() before sending to the channel, the reason behind this is the limit indicates the end of the active buffer content, and position is set back to 0 means that from position to limit the buffer data need to accessJAVA API buffer.flip( );The rewind( ) method is similar to flip( ) but does not affect the limit.
  8. Access data from buffer,there are two methods hasRemaining() and remaining() that will tell you if you&apos;ve reached the buffer&apos;s limit when draining. The boolean method hasRemaining() Tells whether there are any elements between the current position and the limit, and true if, and only if, there is at least one element remaining in this buffer.Theint method remaining() returns the number of elements between the current position and the limit.
  9. Buffer fourth important attribute is called mark() and it’s remain undefined until it set. In this example we have mark the position 2. if we reset now then position will set to the mark. Mark can be used as abstraction on buffer as it’s gives the control how many bytes of data need to be sent over the channel.
  10. In this example we will see how the buffers are compared. Buffer usually implements the comparable interfaces which gives equals( ) method for testing the equality of two buffers and a compareTo( ) method for comparing buffersThe example shows buffer1 and buffer2 are equals as they have same number of remaining elements and also satisfied the criteria that says two buffers are equals.
  11. We talked lot about the Buffers, now let us understand how we can create it there are two methods two perform this the allocate and wrap methods. Before you can read or write, you must have a buffer. To create a buffer, you must allocate it. We allocate a buffer using the static method of allocate().You can also turn an existing array into a buffer, as shown here: byte array[] = new byte[1024]; ByteBuffer buffer = ByteBuffer.wrap( array ); In this case, you&apos;ve used the wrap() method to wrap a buffer around an array.
  12. Duplicating a buffer means Creating a new byte buffer that shares this buffer&apos;s content. The content of the new buffer will be that of this buffer. Changes to this buffer&apos;s content will be visible in the new buffer, and vice versa; the two buffers&apos; position, limit, and mark values will be independent. The new buffer&apos;s capacity, limit, position, and mark values will be identical to those of this buffer. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only.
  13. Buffer slicing means creating a kind of sub-buffer from an existing buffer. That is, it.The content of the new buffer will start at this buffer&apos;s current position. Changes to this buffer&apos;s content will be visible in the new buffer, and vice versa; the two buffers&apos; position, limit, and mark values will be independent
  14. ByteBuffer is biased over network and also knows as Direct buffer, this is special buffer and having few characteristics.A direct buffer is one whose memory is allocated in a special way to increase I/O speed.Thanks for watching the video, do watch the next video on ByteBuffer explained and subscribe to the channel.