请问Android如何释放ByteBuffer.allocateDirect申请的内存
我在制作一个3D测试应用的时候遇到一个问题,这是一个地球3D模型应用,使用ByteBuffer.allocateDirect申请堆外内存,反复多次进出该应用之后,就会出现OOM现象。在网上查了很多关于ByteBuffer.allocateDirect的资料,没有找到解决办法,请教下高手如何解决?
申请内存:
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为int型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
释放:
1、第一种说法是触发full gc就会回收,但是每次进入和退出应用都调用System.gc()没有起作用,资料说jvm的堆外内存无法通过System.gc()释放。所以这种方法我没试验成功。
2、第二种说法:import sun.nio.ch.DirectBuffer ,((DirectBuffer)vbb).cleaner().clean(),但是找不到sun.nio.ch.DirectBuffer 这个类,无法import。
3、第三种说法是反射机制,但是运行时发现getMethod("cleaner")的cleaner找不到出错
Method cleanerMethod = buffer.getClass().getMethod("cleaner");
cleanerMethod.setAccessible(true);
Object cleaner = cleanerMethod.invoke(buffer);
Method cleanMethod = cleaner.getClass().getMethod("clean");
cleanMethod.setAccessible(true);
cleanMethod.invoke(cleaner);
AndroidRuntime Exception:
09-01 15:46:46.212 29144 5690 E AndroidRuntime: FATAL EXCEPTION: GLThread 7970
09-01 15:46:46.212 29144 5690 E AndroidRuntime: Process: com.test.earth, PID: 29144
09-01 15:46:46.212 29144 5690 E AndroidRuntime: java.lang.OutOfMemoryError: Failed to allocate a 3110412 byte allocatio
n with 1374136 free bytes and 1341KB until OOM
09-01 15:46:46.212 29144 5690 E AndroidRuntime: at com.test.earth.component.TestActivity$Ball.<init>(TestActivity.java:562)
09-01 15:46:46.212 29144 5690 E AndroidRuntime: at com.test.earth.component.TestActivity$SceneRenderer.
onSurfaceCreated(TestActivity.java:273)
09-01 15:46:46.212 29144 5690 E AndroidRuntime: at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
09-01 15:46:46.212 29144 5690 E AndroidRuntime: at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:
1259)