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

huangapple go评论76阅读模式
英文:

Does Garbage Collector run in JVM created from C++?

问题

我有一个C++代码库,其中我正在使用JNI来创建JVM并偶尔与一个用Java实现的库进行交互。我很好奇在这种情况下,Java的垃圾收集器是否仍然会可靠地运行和清理呢?

我在网上找到的大多数与JNI相关的信息似乎都是关于“相反”的用例,人们通常主要拥有Java代码,有时通过JNI与本机代码进行交互。对于这种用例,例如在这个网页上有如下说明:

> 对于不再在作用域内的局部引用进行自动垃圾收集,在大多数情况下可以防止内存泄漏。这种自动垃圾收集发生在本地线程返回到Java(本地方法)或从JVM分离(调用API)。如果不进行自动垃圾收集,则可能出现局部引用内存泄漏。如果本地方法不返回到JVM,或者使用调用API的程序不从JVM分离,可能会发生内存泄漏。

我不太确定在这种情况下,“返回到Java”在这里是什么意思。仅从C++偶尔调用基于Java的方法是否足够?那是否已经算作是“返回到Java”了?如果不是,是否有任何方法可以确保垃圾收集器有机会在我的用例中运行?

英文:

I have a C++ codebase, in which I'm using JNI to create a JVM and occasionally interact with a library implemented in Java. I'm curious whether, in this use case, Java's garbage collector will still reliably run and clean up?

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. 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). 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.

I'm not sure what exactly "returns to Java" in this context means. Is just occasionally calling into Java-based methods from C++ sufficient, does that already count as "returning to Java"? If not, are there any ways to make sure that the garbage collector gets a chance to run in my use case?

答案1

得分: 1

通过JNI创建的JVM是一个完整的JVM,包括垃圾回收。

可以这样考虑:通常用于运行Java程序的java命令,实际上只是一个小型JNI程序,它创建一个JVM,找到命令行上指定的类,并对main(String[])方法进行静态调用。

英文:

The JVM created with JNI is a full JVM, including 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.

huangapple
  • 本文由 发表于 2020年9月15日 23:23:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63905028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定