I tried to search online, but did not find answers.
Based on the java doc, ByteBuffer.wrap() create a new ByteBuffer in each call. In a long-running application, if the gc is not triggered, but the app has been continuously calling ByteBuffer.wrap(), the application may use a lot more memory out side of the java heap, and cause potential memory leak. Is is right?
public static ByteBuffer wrap(byte[] array)
Wraps a byte array into a buffer.
The new buffer will be backed by the given byte array; that is, modifications
to the buffer will cause the array to be modified and vice versa. The new
buffer's capacity and limit will be array.length, its position will be zero,
and its mark will be undefined. Its backing array will be the given array, and
its array offset will be zero.
Based on the jdk code, it seems that the answer is no, as ByteBuffer.wrap() creates a new HeapByteBuffer object, but did not allocate a new buffer underneath.
public static ByteBuffer wrap(byte[] array,
int offset, int length)
{
try {
return new HeapByteBuffer(array, offset, length);
} catch (IllegalArgumentException x) {
throw new IndexOutOfBoundsException();
}
}
It's only an issue if you are keeping hard references of the arrays or the wrapping ByteBuffers.
The "wrap" method does not allocate memory out side of the heap like a direct ByteBuffer. The garbage collector should be able to clean it up before an OutOfMemory error occurs.