Memory management when hosting JVM from C++
843829Aug 3 2007 — edited Aug 3 2007We are creating JVM from our C++ program with JNI_CreateJavaVM. I wonder how JVM manages references to Java objects kept in C++ code. Documentation explains how global references work, but this considers Java -> Native path (Java calls native method, after call returns it garbage collects all Java objects created in it unless they explicitly made globally referenced). What will happen if native code initialized JVM and created a lot of Java objects? How JVM would know that Java object is no longer needed and may be garbage collected?
Very simple example (C++-like pseudo-code):
main()
{
JNI_CreateJavaVM(&m_JVM, (void**)&m_jvmEnv, &vm_args);
CallSomeMethod(m_jvmEnv);
...
CallAnotherMethod(m_jvmEnv);
}
void CallSomeMethod(m_jvmEnv)
{
jstring jstr = jvmEnv->NewStringUTF("abc");
}
See that CallSomeMethod allocates a new Java String object. How JVM would know that reference to it is local and object may be garbage collected after the method returns? Would DeleteLocalRef help?