Skip to content

Commit

Permalink
JavaKit: always use ambient javaEnvironment on Android
Browse files Browse the repository at this point in the history
This is not a real fix, I suspect the real fix is to remove javaEnvironment as
an instance variable on all platforms and always use the ambient environment
(as the JNI specification clearly states the environment cannot be shared
between threads).

Works around: swiftlang#157
  • Loading branch information
lhoward committed Nov 9, 2024
1 parent fa5d629 commit fd10935
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Sources/JavaKit/JavaObjectHolder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,21 @@ import JavaRuntime
/// while this instance is live.
public class JavaObjectHolder {
public private(set) var object: jobject?
#if canImport(Android)
public var environment: JNIEnvironment {
try! JavaVirtualMachine.shared().environment()
}
#else
public let environment: JNIEnvironment
#endif

/// Take a reference to a Java object and promote it to a global reference
/// so that the Java virtual machine will not garbage-collect it.
public init(object: jobject, environment: JNIEnvironment) {
self.object = environment.interface.NewGlobalRef(environment, object)
#if !canImport(Android)
self.environment = environment
#endif
}

/// Forget this Java object, meaning that it is no longer used from anywhere
Expand Down

0 comments on commit fd10935

Please sign in to comment.