简体   繁体   English

垃圾收集器是否在从 C++ 创建的 JVM 中运行?

[英]Does Garbage Collector run in JVM created from C++?

I have a C++ codebase, in which I'm using JNI to create a JVM and occasionally interact with a library implemented in Java.我有一个 C++ 代码库,其中我使用 JNI 创建一个 JVM,并偶尔与用 Java 实现的库进行交互。 I'm curious whether, in this use case, Java's garbage collector will still reliably run and clean up?我很好奇,在这个用例中,Java 的垃圾收集器是否仍能可靠地运行和清理?

Most of the information that I find online about JNI seems to be about the "opposite" use case, where people generally appear to have mainly Java code, which sometimes interacts with native code through JNI.我在网上找到的关于 JNI 的大部分信息似乎都是关于“相反”用例的,在这种用例中,人们通常主要使用 Java 代码,有时通过 JNI 与本机代码进行交互。 For such a use case, I find for example the following online :对于这样的用例,我在网上找到了例如以下内容:

The automatic garbage collection of local references that are no longer in scope prevents memory leaks in most situations.在大多数情况下,不再在范围内的本地引用的自动垃圾收集可以防止内存泄漏。 This automatic garbage collection occurs when a native thread returns to Java (native methods) or detaches from the JVM (Invocation API).当本机线程返回到 Java(本机方法)或与 JVM 分离(调用 API)时,会发生这种自动垃圾回收。 Local reference memory leaks are possible if automatic garbage collection does not occur.如果不发生自动垃圾收集,则可能会发生局部引用内存泄漏。 A memory leak might occur if a native method does not return to the JVM, or if a program that uses the Invocation API does not detach from the JVM.如果本机方法未返回到 JVM,或者使用调用 API 的程序未从 JVM 分离,则可能会发生内存泄漏。

I'm not sure what exactly "returns to Java" in this context means.我不确定在这种情况下“返回 Java”究竟是什么意思。 Is just occasionally calling into Java-based methods from C++ sufficient, does that already count as "returning to Java"?只是偶尔从 C++ 调用基于 Java 的方法就足够了,这是否已经算作“回归 Java”? If not, are there any ways to make sure that the garbage collector gets a chance to run in my use case?如果没有,有什么方法可以确保垃圾收集器有机会在我的用例中运行?

The JVM created with JNI is a full JVM , including GC.用 JNI 创建的 JVM 是一个完整的 JVM ,包括 GC。

Think of it this way: The java command that you normally use to run Java programs, is nothing but a small JNI program that creates a JVM, locates the class named on the command-line, and makes a static call to the main(String[]) method.可以这样想:通常用于运行 Java 程序的java命令只不过是一个小型 JNI 程序,它创建了一个 JVM,定位在命令行中命名的类,并对main(String[])方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM