Skip to content

Support concurrent use of a shared JavaVirtualMachine #69

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

Merged
merged 6 commits into from
Oct 11, 2024

Conversation

DougGregor
Copy link
Member

The JavaVirtualMachine class was not at all designed with concurrency in mind: it always created a new Java VM under the hood, and was associated with a single JNI environment even though different threads could have different JNI environments.

Move to a different model with a static shared() method to create or access a shared JavaVirtualMachine instance to encapsulate the (singleton) JVM. If there is an existing JVM, whether created via this Swift library or from some other code, it will be adopted by the shared JavaVirtualMachine instance.

Additionally, the JavaVirtualMachine no longer stores a JNI environment. Instead, it now provides an environment function that queries the JVM to get the JNI environment for the current thread. If the current thread isn't attached to the JVM, it does so and provides the resulting JNI environment.

With all of these in place, we no longer need to force all of our JavaKit tests over to the main actor.

Instead of having the JavaVirtualMachine instance keep track of the JNI
environment for the thread in which it was initialized, provide a JNI
environment query function that attaches the current thread to the JVM
if needed. This lets us query the JNI environment for multiple threads,
should we want to.

We no longer need to force all of the JavaKit runtime tests to the main
actor.
Java implementations have a longstanding limitation that there may only
be one Java Virtual Machine instance per process. Take advantage of this
to provide a shared JavaVirtualMachine instance, initialized on first
use, that can be accessed from any thread. This eliminates the need
to force JavaVirtualMachine creation to be on the main actor, since we
can do it from any thread and get the same result.
This also cleans up various error-handling code paths that were doing
narrow checks.
@DougGregor
Copy link
Member Author

Merging because I'm building other things on top of this

@DougGregor DougGregor merged commit fab398b into swiftlang:main Oct 11, 2024
9 of 10 checks passed
@DougGregor DougGregor deleted the shared-jvm branch October 11, 2024 20:20
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

Successfully merging this pull request may close these issues.

1 participant