为什么"JNI全局"引用具有“最大数量限制"? [英] Why does JNI Global reference have Maximum number limit?

查看:134
本文介绍了为什么"JNI全局"引用具有“最大数量限制"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,JNI是Java和C ++之间的桥梁.最近,我正在为Java项目编码,它的主要模块基于C ++,该C ++需要存储大量的GlobalReference.随着活动的开展,它将增加.因此,GlobalReferences的最大数量(65535)成为一个严重的问题,我必须使用特殊的方法来解决该问题.

所以我对为什么GlobalReferences受到限制感兴趣. 它是否仅用于检测内存泄漏解决方案

据我了解,这并不是要真正检测内存泄漏,而是要完全管理内存. (显然,对于内存泄漏,您在本机代码中挂在Java对象上的时间不应长于全局引用(无论是否具有全局引用).)全局引用的使用在某种程度上是一种反模式(当用于可能存在问题的情况时)通过其他方式解决)),在大多数语言中都是afaik.

可以这么说,使用JNI的事情是您的本机代码处于从属模式. JVM无法清除您在C代码中保留的内容,尤其是全局引用(因为它们的生命周期是不确定的),因此这些限制是防止开发人员滥用JNI并开枪射击的一种措施.

此外,我对于您要完成的任务有点好奇,因为您必须存储超过65k的全局引用-我有一种感觉,您要尝试完成的事情允许使用一种不同的方法,不会将JNI推到极限.

例如现在,我正在将本机数据库库连接到Android应用程序,整个设置必须来回抛出数十万个数据库记录,即使在这种情况下,它的解决方案也不会溢出本地引用表(512 ref限制),更不用说全局引用表了.

我知道可能已经晚了,但是如果您愿意分享您的实际任务,我们也许可以提出适当的处理方式.

As we known, JNI is a bridge between Java and C++. Recently i'm coding for a Java project and it's main module is based on C++ which need to store a large number of GlobalReference. And it will increase along with activity being opened. Therefore the maximum number (65535) of GlobalReferences become a serious problem and i have to solve the problem using peculiar method.

So i'm interested in why there is a limit on GlobalReferences. Is it only for detecting the memory leaks as other's saying?

解决方案

To my understanding, it's not about detecting memory leaks really, it's about just managing memory altogether. (As for memory leaks, obviously, you shoudn't hang on to a Java object in your native code longer than you have to, global ref or not) Usage of global references is somewhat of an antipattern (when used for problems that can be solved by other means) in most languages, afaik.

Thing with JNI is that your native code is in slave mode, so to say. The JVM is unable to clean up stuff you hold on to in your C code, especially global refs ('cause their lifecycle is indefinite), so these limits are a measure to prevent developers from abusing JNI and shooting themselves in the foot.

Also, I'm a bit curious on what task you're trying to accomplish that you have to store over 65k global references -- I have a feeling that what you're trying to accomplish allows for a different approach, one that doesn't push JNI over the edge.

E.g. right now I'm wiring a native database library to an Android app, the whole setup has to throw hundreds of thousands of db records back and forth and even this case has a solution that doesn't overflow even the local ref table (512 ref limit) let alone the global ref table.

I know it's probably late, but if you care to share your actual task, we might be able to come up with a proper way of dealing with it.

这篇关于为什么"JNI全局"引用具有“最大数量限制"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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