RamPrakash
RamPrakash

Reputation: 3322

Use of Java non direct buffer

I did search a lot and checked multiple answers.. none of them is clear to me.


Java has ByteBuffer. It has 2 flavors. 1 is direct and the other one is non-direct. The direct buffer is good for IO.

What is the need for non-direct bytebuffer when we have byte[]? When to use that?

Upvotes: 0

Views: 161

Answers (1)

postFix
postFix

Reputation: 385

non-direct ByteBuffers are stored in the heap and are backed by an underlying byte array. These are typically used when you need a buffer that is readable and writable by the Java application, but doesn't need the same level of performance as a direct ByteBuffer.

So why not always use direct ByteBuffer?

  1. Garbage Collection: Non-direct ByteBuffers are subject to garbage collection, which can free up memory automatically when it is no longer needed. With direct ByteBuffers, you have to manually free the memory.
  2. Concurrency: Direct ByteBuffers are not thread-safe and require explicit synchronization in order to be safely accessed by multiple threads, which can add complexity and overhead to your code.
  3. Complexity: Direct ByteBuffers often require more manual handling and can involve working with native code, which can make them more complex and harder to work with than non-direct ByteBuffers.
  4. Increased Latency: Direct ByteBuffers can have increased latency compared to non-direct ByteBuffers, as the memory is allocated outside of the Java heap and must be transferred to and from the native heap.
  5. Performance Variation: Performance with direct ByteBuffers can vary depending on the underlying system and hardware, making it harder to predict and guarantee performance.

Upvotes: 2

Related Questions