JNI: Overhead of holding Java object references within the native code?
I am looking into integrating a JRE into a C++ a开发者_C百科pplication via JNI.
What is the overhead of holding a large number of references to Java objects within the C++ application (global references in JNI parlance)?
Are there any problems I should be aware of with this approach (other than the obvious, such as manually deallocating the references)?
(a) the overhead is the same as if you were doing it from Java. You are preventing the objects from being garbage-collected.
(b) Holding object references across JNI calls can be fatal to the JVM unless you do it correctly. You need to read carefully the section on Global and Local References in the JNI specification. You also need to consider using Weak References instead of global ones.
This is more of an opinion than an answer but, considering you have the choice, i would strongly recommend not using JNI and rather communicate between your C++ application and the Java VM using another mechanism like Sockets or web-services. If you get it right the JNI solution will clearly be much faster than either of this alternatives but if performance is not crucial then my experience of JNI is that it is best avoided.
As EJP correctly points out (+1) if you do not manage your JNI Java-objects correctly very bad things will happen - including the VM simply dying. I've also found JNI code very hard to test.
精彩评论