ByteBuffer.wrap(byte [])会导致长时间运行的应用程序出现内存泄漏吗? [英] Will ByteBuffer.wrap(byte[]) cause memory leak for long-running applications?

查看:198
本文介绍了ByteBuffer.wrap(byte [])会导致长时间运行的应用程序出现内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在线搜索,但没有找到答案。

I tried to search online, but did not find answers.

基于 java doc ,ByteBuffer.wrap()在每次调用中创建一个新的ByteBuffer。在长时间运行的应用程序中,如果未触发gc,但应用程序一直在调用ByteBuffer.wrap(),则应用程序可能会在Java堆外部使用更多内存,并导致潜在的内存泄漏。是对的吗?

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.

基于jdk代码,似乎答案是否定的,因为ByteBuffer.wrap()创建一个新的HeapByteBuffer对象,但没有在下面分配一个新的缓冲区。

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();
    }
}


推荐答案

这是如果您保留数组的硬引用或包装ByteBuffers,则只会出现问题。

It's only an issue if you are keeping hard references of the arrays or the wrapping ByteBuffers.

wrap方法不会像直接ByteBuffer那样在堆外部分配内存。垃圾收集器应该能够在发生OutOfMemory错误之前清理它。

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.

这篇关于ByteBuffer.wrap(byte [])会导致长时间运行的应用程序出现内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆