Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to use one single JVM on multiple invocations #109

Closed
davidjwriter opened this issue May 15, 2024 · 4 comments
Closed

Is there a way to use one single JVM on multiple invocations #109

davidjwriter opened this issue May 15, 2024 · 4 comments

Comments

@davidjwriter
Copy link

I have a use case where I want my Rust program to act as a middle man from JavaScript to Java code. But don’t want to have to rebuild a new JVM on every invocation. Is there a way to create a constantly running JVM and then re-attach to that JVM every time I call into Rust?

@astonbitecode
Copy link
Owner

j4rs creates one JavaVM per process. This is done implicitly the first time someone uses JvmBuilder::buiid(). j4rs checks whether the JavaVM is created and if not, it creates one.

The Jvm returned by JvmBuilder::build contains a JNINativeInterface, which is attached to the running rust thread. Therefore, when you want to have a new Jvm, JavaVM is not created again; what happens is actually just attaching to the new thread. If you create one more Jvm in the same thread, no attaching is done and this is considered a no-op (you may check the JNI specification for more details).

That being said, you can be explicit and if you know that you have created a Jvm earlier in the process, you can use the Jvm::attach_thread to get a Jvm. Generally, you can save Jvms in thread local, but you cannot use the same Jvm in multiple threads: Jvm is not Send.

Note: Jvm is not Send, but Instances returned by invocations are Send and can be safely used by different threads.

@davidjwriter
Copy link
Author

Ok, that sounds like great news! Thanks for the explanation!

I'm trying to test this out to see if it works, but running into issues building with wasm-pack. Have you successfully built J4RS projects to wasm before?

@astonbitecode
Copy link
Owner

I have not tried using in wasm, but users opened this and this issue, please read the discussions.

In the latter one, the dev claims they achieved what they wanted. The former, had issues, but since then, we have in j4rs the no-runtime-libloading feature, which could resolve the issue this dev had.

@davidjwriter
Copy link
Author

Those are my exact errors I'm running into with the libc stuff. I'll look through them, thanks for the quick responses!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants