GC.AddMemoryPressure等同于Java [英] GC.AddMemoryPressure equivalent in Java

查看:162
本文介绍了GC.AddMemoryPressure等同于Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

项目:Java,JNI(C ++),Android。



我将通过创建托管包装类来管理本机C ++对象的生命周期,指向本地对象的指针(作为一个长成员),并将在其重写的finalize()方法中删除本地对象。有关详细信息,请参见此问题



C ++对象不会占用其他类型的资源,只会占用内存。该对象的内存占用不是非常高,但它实质上高于Java中的64位长。有没有什么办法可以告诉Java的GC,我的包装不仅仅是一个长期价值的责任,在运行垃圾收集之前创建数百万个这样的对象并不是一个好主意?在.NET中,有一个GC的 AddMemoryPressure ()方法,就是为了这个目的。在Java中有相当于什么?

解决方案

在使用更多的Google搜索之后,我发现了一个 good article from IBM Research Center。



简要介绍,他们推荐使用Java堆而不是本机堆作为本地对象。通过这种方式,JVM垃圾收集器的内存压力对于通过句柄从Java代码引用的本地对象来说更为实际。为了达到这个目的,需要覆盖默认的C ++堆分配和取消分配功能:操作员新操作员和操作员删除操作。在operator new中,如果JVM可用(JNI_OnLoad已经被调用),那么调用NewByteArray和GetByteArrayElements,它返回所需的分配内存。为了保护创建的ByteArray不被垃圾收集,还需要为其创建NewGlobalRef,并将其存储在同一个分配的内存块中。在这种情况下,我们需要根据请求分配尽可能多的内存,以及引用的内存。在运算符delete中,需要DeleteGlobalRef和ReleaseByteArrayElements。如果JVM不可用,则使用原生malloc和免费函数。


Project: Java, JNI (C++), Android.

I'm going to manage native C++ object's lifetime by creating a managed wrapper class, which will hold a pointer to the native object (as a long member) and will delete the native object in it's overridden finalize() method. See this question for details.

The C++ object does not consume other types of resources, only memory. The memory footprint of the object is not extremely high, but it is essentially higher than 64 bit of a long in Java. Is there any way to tell Java's GC, that my wrapper is responsible for more than just a long value, and it's not a good idea to create millions of such objects before running garbage collection? In .NET there is a GC's AddMemoryPressure() method, which is there for exactly this purpose. Is there an equivalent in Java?

解决方案

After some more googling, I've found a good article from IBM Research Center.

Briefly, they recommend using Java heap instead of native heap for native objects. This way memory pressure on JVM garbage collector is more realistic for the native objects, referenced from Java code through handles.

To achieve this, one needs to override the default C++ heap allocation and deallocation functions: operator new and operator delete. In the operator new, if JVM is available (JNI_OnLoad has been already called), then the one calls NewByteArray and GetByteArrayElements, which returns the allocated memory needed. To protect the created ByteArray from being garbage collected, the one also need to create a NewGlobalRef to it, and store it e.g. in the same allocated memory block. In this case, we need to allocate as much memory as requested, plus the memory for the references. In the operator delete, the one needs to DeleteGlobalRef and ReleaseByteArrayElements. In case JVM is not available, the one uses native malloc and free functions instead.

这篇关于GC.AddMemoryPressure等同于Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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