如何在 Java 中垃圾收集直接缓冲区 [英] How to garbage collect a direct buffer in Java

查看:42
本文介绍了如何在 Java 中垃圾收集直接缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内存泄漏,我已将其隔离为错误处置的直接字节缓冲区.

I have a memory leak that I have isolated to incorrectly disposed direct byte buffers.

ByteBuffer buff = ByteBuffer.allocateDirect(7777777);

GC 收集包含这些缓冲区的对象,但不会处理缓冲区本身.如果我实例化足够多的包含缓冲区的瞬态对象,我会收到以下令人鼓舞的消息:

The GC collects the objects that harbor these buffers but does not dispose of the buffer itself. If I instantiate enough of the transient objects containing buffers, I get this encouraging message:

java.lang.OutOfMemoryError: Direct buffer memory

我一直在寻找这个问题,显然

I have been searching up this problem and apparently

buff.clear();

System.gc();

不工作.

推荐答案

我怀疑您的应用程序在某处引用了 ByteBuffer 实例,这阻止了它被垃圾收集.

I suspect that somewhere your application has a reference to the ByteBuffer instance(s) and that is preventing it from being garbage collected.

直接 ByteBuffer 的缓冲内存分配在普通堆之外(这样 GC 不会移动它!!).但是,ByteBuffer API 没有提供显式处置/取消分配缓冲区的方法.所以我假设垃圾收集器会这样做……一旦它确定不再引用 ByteBuffer 对象.

The buffer memory for a direct ByteBuffer is allocated outside of the normal heap (so that the GC doesn't move it!!). However, the ByteBuffer API provides no method for explicitly disposing of / deallocating a buffer. So I assume that the garbage collector will do it ... once it determines that the ByteBuffer object is no longer referenced.

这篇关于如何在 Java 中垃圾收集直接缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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