Java Reference
In-Depth Information
48. Do not use direct buffers for short-lived, infrequently used objects
ThenewI/O(NIO)classesin java.nio allowthecreationanduseofdirectbuffers.These
buffers tremendously increase throughput for repeated I/O activities. However, their cre-
ation and reclamation is more expensive than the creation and reclamation of heap-based
non-directbuffersbecausedirectbuffersaremanagedusingOS-specificnativecode.This
added management cost makes direct buffers a poor choice for single-use or infrequently
used cases. Direct buffers are also outside the scope of Java's garbage collector; conse-
quently, injudicious use of direct buffers can cause memory leaks. Finally, frequent alloc-
ation of large direct buffers can cause an OutOfMemoryError .
Noncompliant Code Example
This noncompliant code example uses both a short-lived local object, rarelyUsed-
Buffer ,andalong-lived,heavilyusedobject, heavilyUsedBuffer .Bothareallocatedin
non-heap memory; neither is garbage collected.
Click here to view code image
ByteBuffer rarelyUsedBuffer = ByteBuffer.allocateDirect(8192);
// Use rarelyUsedBuffer once
ByteBuffer heavilyUsedBuffer = ByteBuffer.allocateDirect(8192);
// Use heavilyUsedBuffer many times
Compliant Solution
This compliant solution uses an indirect buffer to allocate the short-lived, infrequently
used object. The heavily used buffer appropriately continues to use a non-heap, non-
garbage-collected direct buffer.
Click here to view code image
ByteBuffer rarelyUsedBuffer = ByteBuffer.allocate(8192);
// Use rarelyUsedBuffer once
ByteBuffer heavilyUsedBuffer = ByteBuffer.allocateDirect(8192);
// Use heavilyUsedBuffer many times
Search WWH ::




Custom Search