Use of Java non direct buffer

huangapple go评论62阅读模式
英文:

Use of Java non direct buffer

问题

Java有ByteBuffer。它有两种类型。一种是直接(direct),另一种是非直接(non-direct)。
直接缓冲区适用于IO。

当我们有byte[]时,为什么需要非直接ByteBuffer?什么时候使用它?

英文:

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?

答案1

得分: 2

非直接的ByteBuffer存储在堆上,并由底层字节数组支持。通常在需要可由Java应用程序进行读写的缓冲区,但不需要与直接ByteBuffer相同性能水平的情况下使用它们。<br>

那为什么不总是使用直接ByteBuffer呢?<br>

  1. 垃圾回收:非直接ByteBuffer受到垃圾回收的影响,当不再需要时,它可以自动释放内存。而对于直接ByteBuffer,您必须手动释放内存。
  2. 并发性:直接ByteBuffer不是线程安全的,需要显式同步才能被多个线程安全访问,这可能会给您的代码增加复杂性和开销。
  3. 复杂性:直接ByteBuffer通常需要更多的手动处理,可能涉及与本机代码一起工作,这可能会使它们比非直接ByteBuffer更复杂,更难处理。
  4. 增加的延迟:与非直接ByteBuffer相比,直接ByteBuffer可能具有增加的延迟,因为内存分配在Java堆之外,必须在本机堆和Java堆之间进行传输。
  5. 性能变化:直接ByteBuffer的性能取决于底层系统和硬件,这使得难以预测和保证性能。
英文:

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.<br>

So why not always use direct ByteBuffer?<br>

  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.

huangapple
  • 本文由 发表于 2023年2月14日 05:48:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定