Sunday 16 June 2019

NIO: Direct and indirect buffers


There are mainly three types of ByteBuffers.
a.   Direct
b.   Indirect and
c.    Mapped byte buffers.

In this post, I am going to discuss about direct and indirect byte buffers. My next post will explain about memory mapped byte buffers.

Direct vs. indirect buffers
Direct byte buffer is a special kind of buffer, whose memory allocation is happened in special way to increase the I/O operations speed. From the java doc, I understood that the behavior of direct byte buffers is implementation dependent.

I copied below statements from the oracle Javadoc of the class java.nio.ByteBuffer.

The contents of direct buffers may reside outside of the normal garbage-collected heap, and so their impact upon the memory footprint of an application might not be obvious. It is therefore recommended that direct buffers be allocated primarily for large, long-lived buffers that are subject to the underlying system's native I/O operations. In general, it is best to allocate direct buffers only when they yield a measurable gain in program performance.

How to create direct byte buffer?
ByteBuffer directBuf = ByteBuffer.allocateDirect(5);

How to know, a buffer is directed or not?
'isDirect()' api returns true if the buffer is direct buffer, else false.

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;

public class Test {

 public static void main(String... args) throws IOException {
  ByteBuffer directBuf = ByteBuffer.allocateDirect(10);
  ByteBuffer indirectBuffer = ByteBuffer.allocate(10);

  System.out.printf("is directBuf is directed buffer : %b\n", directBuf.isDirect());
  System.out.printf("is indirectBuffer is directed buffer : %b", indirectBuffer.isDirect());

 }
}

Output
is directBuf is directed buffer : true
is indirectBuffer is directed buffer : false

Are direct buffers are affected by garbage collection?
Direct buffers are working with memory directly, without copying the data into any intermediate buffer (Application memory), it will not get affected by garbage collection. You can read my post ‘What will happen when application request I/O operation?’ to know about memory allocation.





Previous                                                 Next                                                 Home

No comments:

Post a Comment